Angular component
component is Angular application basic构建块, 每个componentpackage含模板, class and 样式.
提示
in Angular in, component遵循单一职责principles, 每个component只负责一个specific functions or 视graph.
1. componentstructure
一个典型 Angular componentpackage含以 under 部分:
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-angular-app';
}
2. component装饰器
@Component 装饰器用于定义component 元data, including:
selector: component CSS 选择器, 用于 in 模板in引用componenttemplateUrl: component模板file pathtemplate: in 联模板string ( and templateUrl 二选一)styleUrls: component样式file patharraystyles: in 联样式array ( and styleUrls 二选一)
模板语法
Angular providing了丰富 模板语法, 用于 in 模板 and component之间建立data绑定.
warning
模板语法 is Angular 特 has , and Vue or React 模板语法 has 明显区别, 需要特别注意.
1. data绑定
Angular support many 种data绑定方式:
- 插值绑定:
{{ value }}, 用于显示componentdata - property绑定:
[property]="value", 用于绑定 HTML property - event绑定:
(event)="handler()", 用于绑定 DOM event - 双向绑定:
[(ngModel)]="value", 结合了property绑定 and event绑定
2. 指令
指令 is Angular 模板in 特殊标记, 用于scale HTML 元素 functions. 主要分 for 三class:
- component指令: 带 has 模板 指令 (即component本身)
- structure指令: 改变 DOM structure 指令, such as
*ngIf,*ngFor - property指令: 改变元素 out 观 or behavior 指令, such as
ngStyle,ngClass
3. 管道
管道用于 in 模板in转换data显示, Angular providing了 many 种 in 置管道:
{{ currentDate | date:'yyyy-MM-dd' }}
{{ price | currency:'CNY' }}
{{ text | uppercase }}
creation自定义component
using Angular CLI 可以 fast 速creation自定义component:
ng generate component my-component
component通信
component之间可以through many 种方式for通信:
- @Input: 父component向子component传递data
- @Output: 子component向父component发送event
- ViewChild: 父component访问子componentinstance
- Service: throughservice in component间共享data
练习 1: creation自定义component
- using Angular CLI creation一个名 for
user-profilecomponent - in componentin定义
@Inputpropertyuser, package含nameandemail字段 - in 父componentinusing该component, 并传递userdata
练习 2: using模板语法
- in componentin定义一个array
items, package含几个string元素 - in 模板inusing
*ngFor遍历array并显示每个元素 - 添加一个输入框, using
[(ngModel)]implementation双向绑定 - 添加一个按钮, using
(click)event绑定, 点击 after 添加 new 元素 to array