angular 自定义组件

自定义组件 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; // ... }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值