AppComponent
壳的三个实现文件:
-
app.component.ts
— 组件的类代码,这是用 TypeScript 写的。 -
app.component.html
— 组件的模板,这是用 HTML 写的。 -
app.component.css
— 组件的私有 CSS 样式。
添加组件 heroes 后 生产的类文件代码:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] }) export class HeroesComponent implements OnInit { constructor() { } ngOnInit() { } }
在组件类中,需要从 Angular 核心库中导入 Component
符号,并为组件类加上 @Component
装饰器。
import { Component, OnInit } from '@angular/core';
@Component
是个装饰器函数,用于为该组件指定 Angular 所需的元数据。
CLI 自动生成了三个元数据属性:
-
selector
— 组件的选择器(CSS 元素选择器) -
templateUrl
— 组件模板文件的位置。 -
styleUrls
— 组件私有 CSS 样式表文件的位置。
CSS 元素选择器 app-heroes
用来在父组件的模板中匹配 HTML 元素的名称,以识别出该组件。
ngOnInit
是一个生命周期钩子,Angular 在创建完组件后很快就会调用 ngOnInit
。这里是放置初始化逻辑的好地方。
始终要 export
这个组件类,以便在其它地方(比如 AppModule
)导入它。
<h2>{{hero.name | uppercase}} Details</h2>
绑定表达式中的 uppercase
位于管道操作符( | )的右边,用来调用内置管道 UppercasePipe
。
管道 是格式化字符串、金额、日期和其它显示数据的好办法。 Angular 发布了一些内置管道,而且你还可以创建自己的管道。
AppModule
Angular 需要知道如何把应用程序的各个部分组合到一起,以及该应用需要哪些其它文件和库。 这些信息被称为元数据(metadata)。
有些元数据位于 @Component
装饰器中,你会把它加到组件类上。 另一些关键性的元数据位于 @NgModule
装饰器中。
最重要的 @NgModule
装饰器位于顶级类 AppModule 上。
Angular CLI 在创建项目的时候就在 src/app/app.module.ts
中生成了一个 AppModule
类。 这里也就是你要添加 FormsModule
的地方。
导入 FormsModule
打开 AppModule
(app.module.ts
) 并从 @angular/forms
库中导入 FormsModule
符号。
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here
然后把 FormsModule
添加到 @NgModule
元数据的 imports
数组中,这里是该应用所需外部模块的列表。
imports: [
BrowserModule,
FormsModule
],