场景:将报价组件的价格变化传到父组件当中去
ng g component price-quote
在price-quote.component.ts中
import { Component, OnInit,EventEmitter ,Output} from '@angular/core';
@Component({
selector: 'app-price-quote',
templateUrl: './price-quote.component.html',
styleUrls: ['./price-quote.component.css']
})
export class PriceQuoteComponent implements OnInit {
stcokCode:string = "IBM";
price:number;
@Output() //与@Input刚好相反,记得也要用import引入
lastPrice:EventEmitter<PriceQuote> = new EventEmitter(); //准备用它来发射事件
constructor() {
setInterval(()=>{
let priceQuote:PriceQuote = new PriceQuote(this.stcokCode,100*Math.random()); //使用随机函数来模拟股票价格的波动,两个参数一个是股票代码,一个是股票价格
this.price = priceQuote.lastPrice;
this.lastPrice.emit(priceQuote)
},1000)
}
ngOnInit() {
}
}
export class PriceQuote{ //PriceQuote是自定义的一个类
constructor(public stockCode:string,
public lastPrice:number
){
}}
price-quote.component.html
<div>
这里是报价组件
</div>
<div>
股票代码是{{stockCode}},股票价格是{{price |number:"2.2-2"}}
</div>
app.component.ts
import { Component } from '@angular/core';
import {PriceQuote} from "./price-quote/price-quote.component"
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
stock = "";
priceQuote:PriceQuote = new PriceQuote("",0);
//父组件接受数据
priceQuoteHandler(event,PriceQuote){
this.priceQuote = event;
}
}
app.component.html
//这里是通过事件绑定触发并且捕获
<app-price-quote (lastPrice)="priceQuoteHandler($event)"></app-price-quote>
<div>这是在报价组件外部,股票代码是{{priceQuote.stcokCode}}</div>
<div>股票价格是{{priceQuote.lastPrice |number:'2.2-2'}}</div>