@Output输出属性,在组件间传递数据的实例

输出属性:
使用输出属性,向组件外发射事件并通过事件携带数据,这个事件只能由父组件通过事件绑定的方式来捕获并处理

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>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值