##输入输出属性 ###输入属性 使用@input装饰器注解来实现,代码实现如下:
export class OrderComponent implements OnInit {
@Input()
stockCode: string;//用@input装饰器修饰
@Input()
amount: number;
constructor() { }
ngOnInit() {
}
<div>
我是子组件!
</div>
<div>股票代码是{{stockCode}},买了{{amount}}手!</div>
export class AppComponent {
stock = '';
}
<div>
我是父组件!
</div>
<div>
<input type="text" placeholder="请输入购买的股票代码" [(ngModel)]="stock" >//双向绑定自己的属性
<app-order [stockCode]='stock' [amount]="100"></app-order>//父组件引用子组件的时候,给自组件传值
</div>
这种组件间传值的方式,只适用于父组件向自组件传值。
###输出属性
使用@Output装饰器配合EventEmitter来实现子组件向父组件传递数据
示例代码:
export class PriceQuoteComponent implements OnInit {
private stockCode = 'NKM0083';
private lastPrice: number;
// tslint:disable-next-line:no-output-rename
@Output('myevent')//使用装饰器实现输出数据,参数为被使用的唯一标识,若没有则使用参数名
priceEvent: EventEmitter<PriceQuote> = new EventEmitter();//定义方法
constructor() {
setInterval(() => { //定义定时任务
//赋值
let priceQuote: PriceQuote = new PriceQuote(this.stockCode, 100 * Math.random());
this.lastPrice = priceQuote.price;
this.priceEvent.emit(priceQuote);//往外发送数据
}, 3000);
}
ngOnInit() {
}
}
export class PriceQuote {
constructor(
public stockCode: string,
public price: number
) {
}
}
<div>
这是股票价格子组件,</div>
<div>
股票代码是{{stockCode}},
股票价格是{{lastPrice | number:'2.2-2'}}
</div>
export class AppComponent {
stock = '';
priceQuote: PriceQuote = new PriceQuote('', 0);
doOutput(event: PriceQuote) {
this.priceQuote = event;
}
}
//通过方法绑定的方法实现数据传输
<app-price-quote (myevent)="doOutput($event)"></app-price-quote>
<div>
这是父组件,</div>
<div>
股票代码是{{priceQuote.stockCode}},
股票价格是{{priceQuote.price | number:'2.2-2'}}
</div>
###中间人模式
输入输出模式只能实现子组件到主组件,或者主组件到子组件。当需要实现子组件和子组件之间进行数据传输的时候,需要使用到中间人模式。
其本质就是使用一个父组件(或可注入的服务模块),通过output把数据传输到父组件(服务),再通过input属性,把数据传给另一个子组件。
代码略...