输出属性:
使用输出属性,向组件外发射事件并通过事件携带数据,这个事件只能由父组件通过事件绑定的方式来捕获并处理
1、ng new demo
2、ng g component priceQuote
3、在priceQuote.component.ts内书写代码
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
@Component({
selector: 'app-price-quote',
templateUrl: './price-quote.component.html',
styleUrls: ['./price-quote.component.css']
})
export class PriceQuoteComponent implements OnInit {
// / 2、单独声明2个属性
stockCode:string = " IBM ";
price: number;
// 有多个声明,一定要添加angular/code的,这里需要添加一个泛型:指发射出去的数据具体是什么类型的
// 下面这个对象既可以发射事件也可以订阅事件
// 这个案例里面是发射事件 需要使用@Output()装饰器来注解,可以在()内修改接收点击事件的名字,例如@Output(‘priceChange’)接收事件的时候就是(priceChange)= 'priceQuoteHandler($event)'
@Output()
lastPrice: EventEmitter<PriceQuote> = new EventEmitter();
constructor() {
setInterval(() => {
let priceQuote:PriceQuote = new PriceQuote(this.stockCode, 100*Math.random());
this.price = priceQuote.lastPrice;
// 使用装饰器注解后,就可以使用.emit()一个值出去,这个值就是最新的报价
this.lastPrice.emit(priceQuote);
},1000);
}
ngOnInit() {
}
}// 1、定义一个报价对象,来封装股票价格信息
// 将特定的数据结构用类或接口来明确定义是一个良好的习惯,因为我们使用typescript进行编程,声明类或者接口可以让IDE做类型检查和语法提示
export class PriceQuote {
constructor(
public stockCode:string,
public lastPrice:number
){
}
}
4、在priceQuote内书写代码
<div>这里是报价组件</div>
<div>股票代码是{{stockCode}},股票价格是{{price | number: '2.2-2'}}</div>
5、在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 {
// aaa = "";
priceQuote: PriceQuote = new PriceQuote("", 0);
// 书写一个方法接收$event,这个event的类型就是字组件emit发射过来的类型
priceQuoteHandler(event: PriceQuote) {
this.priceQuote = event;
}
}
6、在app.component.html内书写
<app-price-quote (lastPrice)="priceQuoteHandler($event)"></app-price-quote><br>
<div>这是在报价组件外部,<br>
股票代码是{{priceQuote.stockCode}},
股票的价格是{{priceQuote.lastPrice | number:'2.2-2'}}</div>