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