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