Angular4子组件向父组件传值

场景:将报价组件的价格变化传到父组件当中去

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>
最终效果.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容