组件
组件是Angular应用的主要构造块。每个组件包括如下部分:
- 一个HTML模块,用于声明页面要渲染的内容。
- 一个用户定义行为的Typescript类
- 一个CSS选择器,用于定义组件在模板中的使用方式。
- (可选) 要应用在模板上的CSS样式
创建组件
使用Angular CLI创建一个组件:
- 在终端窗口中,导航到要放置你应用的目录。
- 运行 ng generate component <component - name>命令,其中<component - name>是新组件的名字。
默认情况下,该命令会创建以下内容:
- 一个以该组件命名的文件夹
- 一个组件文件<component - name>.component.ts
- 一个模板组件<component - name>.component.html
- 一个css文件,<component - name>.component.css
- 测试文件 <component - name>.component.spec.ts
其中<component - name>是组件的名称
指定组件的CSS选择器
每个组件都需要一个CSS选择器,选择器会告诉Angular:当在模板HTML中找到相应的标签时,就把该组件实例化在哪里。
在@Component装饰器中添加一个selector语句来指定的选择器。
@Component({
selector: 'app-component-overview',
})
视图封装
目前是没看懂到底有什么用???
组件交互
让两个或多个组件之间共享信息的方法
父传子 - 通过输入型绑定把数据从父组件传到子组件
父组件传入: [hero]="hero" [] 中存放在子组件接收时的变量名 = 后存放父组件传入自组建的值。
import { Component } from '@angular/core';
import { HEROES } from './hero';
@Component({
selector: 'app-hero-parent',
template: `
<h2>{{master}} controls {{heroes.length}} heroes</h2>
// 使用子组件是传入值
<app-hero-child
*ngFor="let hero of heroes"
[hero]="hero"
[master]="master">
</app-hero-child>
`
})
export class HeroParentComponent {
heroes = HEROES;
master = 'Master';
}
子组件:heroChildComponent有两个输入型属性,它们通过@Input 装饰器。
需要导入Input
使用@Input() hero 对应 父组件传入的值
使用@Input('master') mastername = ' ' ; 可以起别名 ()内为父组件传递的值
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-hero-child',
template: `
<h3>{{hero.name}} says:</h3>
<p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
`
})
export class HeroChildComponent {
@Input() hero!: Hero;
@Input('master') masterName = '';
}
通过setter截听输入属性值的变化
子组件同样需要导入Input
export class NameChildComponent {
@Input()
get name(): string { return this._name; }
set name(name: string) {
this._name = (name && name.trim()) || '<no name set>';
}
private _name = '';
}
父组件监听子组件的事件
子组件暴露一个 EventEmitter
属性,当事件发生时,子组件利用该属性 emits
(向上弹射)事件。父组件绑定到这个事件属性,并在事件发生时作出回应。
子组件的 EventEmitter
属性是一个输出属性,通常带有@Output 装饰器,就像在 VoterComponent
中看到的。
emit中存放父组件接收事件时的名字,
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-voter',
template: `
<h4>{{name}}</h4>
<button (click)="vote(true)" [disabled]="didVote">Agree</button>
<button (click)="vote(false)" [disabled]="didVote">Disagree</button>
`
})
export class VoterComponent {
@Input() name = '';
@Output() voted = new EventEmitter<boolean>();
didVote = false;
vote(agreed: boolean) {
this.voted.emit(agreed);
this.didVote = true;
}
}
父组件:
绑定了一个事件处理器(onVoted()
),用来响应子组件的事件($event
)并更新一个计数器。
import { Component } from '@angular/core';
@Component({
selector: 'app-vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<app-voter
*ngFor="let voter of voters"
[name]="voter"
(voted)="onVoted($event)">
</app-voter>
`
})
export class VoteTakerComponent {
agreed = 0;
disagreed = 0;
voters = ['Narco', 'Celeritas', 'Bombasto'];
onVoted(agreed: boolean) {
if (agreed) {
this.agreed++;
} else {
this.disagreed++;
}
}
}