自定义组件 http://www.ngui.cc/news/show-103.html
在 Angular 中,我们可以通过 Component 装饰器和自定义组件类来创建自定义组件。
基础知识
定义组件的元信息
在 Angular 中,我们可以使用 Component 装饰器来定义组件的元信息:
@Component({
selector: 'my-app', // 用于定义组件在HTML代码中匹配的标签
template: `<h1>Hello {{name}}</h1>`, // 定义组件内嵌视图 })
定义组件类
export class AppComponent {
name = 'Angular';
}
定义数据接口
在 TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。
interface Person {
name: string;
age: number;
}
let semlinker: Person = {
name: 'semlinker',
age: 31 };
自定义组件示例
创建 UserComponent 组件
import { Component } from '@angular/core';
@Component({
selector: 'sl-user',
template: `
<h2>大家好,我是{{name}}</h2>
<p>我来自<strong>{{address.province}}</strong>省,
<strong>{{address.city}}</strong>市
</p>
` })
export class UserComponent {
name = 'Semlinker';
address = {
province: '福建',
city: '厦门' };
}
声明 UserComponent 组件
// ... import { UserComponent } from './user.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, UserComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
使用 UserComponent 组件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<sl-user></sl-user>
`,
})
export class AppComponent {}
使用构造函数初始化数据
@Component({...})
export class UserComponent {
name: string;
address: any;
constructor() {
this.name = 'Semlinker';
this.address = {
province: '福建',
city: '厦门' }
}
}
接口使用示例
定义 Address 接口
interface Address { province: string;
city: string;
}
使用 Address 接口
export class UserComponent {
name: string;
address: Address; // ... }