Angular4中的输出属性

Angular4中的输出属性

当子组件需要向父组件传递信息时需要用到输出属性。
举个栗子:当我们从股票交易所获得股票的实时价格时,希望外部也可以得到这个信息。为了方便,这里的实时股票价格我们通过一个随机数来模拟。这里的子组件我们叫它app.price.quote

使用EventEmitter从子组件向外发射事件

price.quote.ts
export class PriceQuoteComponent implements OnInit{
    stockCode: string = 'IBM';
    price: number;

    //使用EventEmitter发射事件
    //泛型是指往外发射的事件是什么类型
    //priceChange为事件名称
    @Output()
    priceChange:EventEmitter<PriceQuote> = new EventEmitter();

    constructor(){
        setInterval(() => {
            let priceQuote = new PriceQuote(this.stockCode, 100*Math.random());
            this.price = priceQuote.lastPrice;
            //发射事件
            this.priceChange.emit(priceQuote);
        })
    }

    ngInit(){
    }
}

//股票信息类
//stockCode为股票代码,lastPrice为股票价格
export class PriceQuote{
    constructor(public stockCode:string,
                public lastPrice:number
    )
}
price.quote.html
<p>
  这里是报价组件
</p>
<p>
  股票代码是{{stockCode}}
</p>
<p>
  股票价格是{{price | number:'2.2-2'}}
</p>

接着我们在父组件中接收事件

app.component.html
<app-price-quote (priceChange)="priceQuoteHandler($event)"></app-price-quote>

<div>
  这是在报价组件外, 股票代码是{{priceQuote.stokcCode}},
  股票价格是{{priceQuote.lastPrice | number:'2.2-2'}}
</div>

事件绑定和原生的事件绑定是一样的,都是将事件名称放在()中。

app.component.ts
export class AppComponent{
    priceQuote:PriceQuote = new PriceQuote('', 0);

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

这里的event类型就是子组件传递事件的类型。
简单的说,就是子组件通过emit发射事件priceChange,并将值传递出来,父组件在使用子组件时会触发priceChange事件,接收到值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值