angular 核心概念之二:组件

120 阅读1分钟

组件:是一段可以反复使用的页面片段,如页头、轮播、手风琴
组件(component)= 模板(template)+ 脚本(script)+ 样式(style)
提示:NG中任何一个组件都必须声明在一个模块中

如何创建一个组件呢?

  1. 创建组件class 装饰器1:@Component()
    import { Component } from "@angular/core";

    // 装饰器(Decorator)--用于指定class的用途
    @Component({
      template: '<h2>我的组件C01</h2><hr/>',
      selector: 'myc01'
    })
    export class MyC01Component {

    }
  1. 在某个模块中注册组件class 装饰器2:@NgModule()
    在app.module.ts中声明注册
    @NgModule({
      declarations: [ // 宣言/声明
        AppComponent,
        MyC01Component,
      ],
    export class AppModule { }
  1. 使用已经注册过的组件
    在app.component.html中使用
    <myc01></myc01>

angular 提供的创建组件的简化工具

    ng generate component 组件名