Angular4学习笔记(六)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dan_2017/article/details/78715733

组价间通信(以一个购买股票的小例子来体现组建通信所学的内容)

(一)输入属性

 效果图:

代码实现如下:

  这里把股票代码scoket和股票数量绑定到scoketCode和amount属性传递给子组件order
  先创建一个子组件order,用来显示子组件的信息

app.component.html

<div>
我是父组件!
</div>
<inputtype="text" [(ngModel)]="scoket"placeholder="请输入股票代码">
<!-- 把文本框输入的scoket绑定到scoketCode这个属性上 -->
<app-order [scoketCode]="scoket" [amount]="100"></app-order>

app.component.ts

scoket="";

order.component.html

<p>
我是子组件!
</p>
买{{amount}}手{{scoketCode}}股票!

order.component.ts

// @Input()指从父组件获取值(子组件的值不能给父组件)
@Input()
amount:number;
@Input()
scoketCode:string;

  (二)输出组件

效果图:

 这里使用EventEmitter对象监听事件并发送给父类(外部)

代码实现如下:

price-quote.component.html

<div>
我是priceQuote组件,用来显示股票最新价格!
</div>
<div>
<!-- 使用管道保留两位整数,两位小数 -->
股票{{scoketCode}},最新报价是{{price | number:'2.2-2'}}!
</div>

price-quote.component.ts

export classPriceQuoteComponent implements OnInit {
scoketCode="IBM";
price:number;
//EventEmitter:是一个对事件进行监听的对象,既可以发送时间,也可以定略事件
@Output()
lastPrice :EventEmitter<PriceQuote> =new EventEmitter();
constructor() {
//setInterval实现股票价格变化,1000代表一秒执行一次
//股票价格用100*Math.random()代替
setInterval(()=>{
let priceQuote :PriceQuote =newPriceQuote(this.scoketCode,100*Math.random());
this.price=priceQuote.lastPrice;
//这里调用emit发送最新价格事件
this.lastPrice.emit(priceQuote);
},1000)
}

ngOnInit() {
}

}
/**
* PriceQuote类
*/
export classPriceQuote{
constructor(publicscoketCode:string,publiclastPrice:number){

}
}

app.component.html

<!-- lastPrice指当前需要捕捉的事件,$event指当前事件 -->
<app-price-quote (lastPrice)="getLastPrice($event)"></app-price-quote>
<hr>
我是父组件!<br>

股票{{priceQuote.scoketCode}},最新报价是{{priceQuote.lastPrice | number:'2.2-2'}}!

app.component.ts

export classAppComponent {
scoket="";

//这里接收发送过来的最新报价
priceQuote :PriceQuote =new PriceQuote("",0);
//获取最新报价 
//event:代表当前事件,指从子组件发送过来的lastPrice
getLastPrice(event:PriceQuote){
this.priceQuote =event;
}
}

(三)中间人模式通信:


效果图:priceQutoe组件上点击购买股票,把最新价格发送给app组件,app组件又发送给order组件


代码如下:

price-qutoe.component.html

<input type="button" value="购买股票" (click)="buySocket()" >

price-qutoe.component.ts

 @Output()
  buy :EventEmitter<PriceQuote> = new EventEmitter();

//当点击购买股票时发送最新报价到中间组件
   buySocket(){
     this.buy.emit(new PriceQuote(this.scoketCode,this.price));
   }

 
 


app.component.html

<app-price-quote (buy)="buyHandler($event)"></app-price-quote>
<hr>
<!-- 把 priceQuote 绑定到priceQuote 上在order组件获取-->
<app-order [priceQuote]="priceQuote"></app-order>
app.component.ts

 buyHandler(event:PriceQuote){
    this.priceQuote = event;
  }


order.component.ts

 @Input()
  priceQuote:PriceQuote;

order.component.html

<p>
  我是子组件!
</p>
买100手{{priceQuote.scoketCode}}股票,价格是:{{priceQuote.lastPrice}}
*****************************************************

这是组建间通信实现的小例子,请大家多多指教!

猜你喜欢

转载自blog.csdn.net/Dan_2017/article/details/78715733
今日推荐