@Input用来让父模块往子模块传递内容,例如:
<app-input [succulent]="succos" [amount]="100">app-input>
[succulent]=”succos” 这个标签可以理解为一个专门的监听器,监听父组件传递过来的succos参数,并存入自身组件的succulent变量;
export class FatherComponent {
data: Array<Object>;
constructor() {
this.data = [
{
"id": 1,
"name": "乒乓福娘"
},
{
"id": 2,
"name": "黄丽"
},
{
"id": 3,
"name": "荷叶莲"
},
{
"id": 4,
"name": "白美人"
},
{
"id": 5,
"name": "石生花"
}
]
}
}
<h1>父组件h1>
// 包含子组件, 并使用属性传递数据过去
<app-child [info]="data">app-child>
export class ChildComponent {
// 使用@Input获取传递过来的数据
@Input()
info: Array
<ul>
<li *ngFor="let item of info">
{{item.name}}
li>
ul>
子模块想自定义一些event传递给父模块要用到@Output
export class InputTestComponent implements OnInit {
price:number;
@Output() priceOut = new EventEmitter();
constructor() {
this.price=10;
}
ngOnInit() {
}
priceChange(){
this.priceOut.emit(this.price);
}
}
<input type="text" placeholder="请输入价格" [(ngModel)]="price" (input)="priceChange()" />
<p>价格为:{{suculentPrice}}p>
<app-child (priceOut)="receivePrice($event)">app-child >
// 函数接受子函数传递过来的变量, 子函数中emit的时候触发这个函数。
suculentPrice=10;
receivePrice(event:number){
this.suculentPrice=event;
}
中间人模式相当于就是同时利用输入输出属性将信息通过两个组件共同的父组件进行组件间通讯,这个共同的父组件就是中间人
<button type="button" (click)="buySuculent($event)">购买多肉button>
export class InputTestComponent implements OnInit {
constructor() {
this.price=10;
this.succulent="水仙花";
}
@Output() buy:EventEmitter=new EventEmitter();
buySuculent(event){
this.buy.emit(new Succo(this.succulent,this.price));
}
}
export class Succo{
constructor(public succulent:string,public price:number){
}
}
<app-child1 (buy)="receiveBuy($event)" >app-child1>
<app-child2 [buyInfo]="buyInfos">app-child2>
export class KnowledgeComponent implements OnInit, AfterViewInit {
buyInfos:Succo=new Succo("",0);
constructor() { }
ngOnInit() {
}
receiveBuy(event:Succo){
this.buyInfos=event;
}
}
<p>收到名称:{{buyInfo.succulent}}p>
<p>收到价格:{{buyInfo.price}}p>
export class BuyComponent implements OnInit {
@Input()
buyInfo:Succo;
constructor() { }
ngOnInit() {
}
}