通过输入型绑定把数据从父组件传到子组件
// 子组件
import { Component, Input } from '@angular/core'; import { Hero } from './hero'; @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: string; }
// 父组件
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'; }
通过setter截听输入属性值的变化
-- 子组件上的Input() name属性上的setter会格式化名字
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-name-child', template: '<h3>"{{name}}"</h3>' }) export class NameChildComponent { private _name = ''; @Input() set name(name: string) { this._name = (name && name.trim()) || '<no name set>'; } get name(): string { return this._name; } }
-- 父组件
import { Component } from '@angular/core'; @Component({ selector: 'app-name-parent', template: ` <h2>Master controls {{names.length}} names</h2> <app-name-child *ngFor="let name of names" [name]="name"></app-name-child> ` }) export class NameParentComponent { // Displays 'Mr. IQ', '<no name set>', 'Bombasto' names = ['Mr. IQ', ' ', ' Bombasto ']; }
To Be Continute ......