AngularJs学习笔记-组件间通讯

组件间通讯

(1)输入属性@Input

Tips:子组件属性的改变不会影响到父组件

如下,子组件中stockCode属性发生变化不会引起父组件stock属性的变化

(2)输入属性@Output

子组件

扫描二维码关注公众号,回复: 5163060 查看本文章
import { Component, OnInit, Output } from '@angular/core';
import { EventEmitter } from '@angular/core';

const STOCK_CODE = "IBM";

@Component({
  selector: 'app-price-quote-inner',
  templateUrl: './price-quote-inner.component.html',
  styleUrls: ['./price-quote-inner.component.css']
})
export class PriceQuoteInnerComponent implements OnInit {
  price: number = 0;

  @Output("priceChange")
  lastPrice: EventEmitter<PriceQuote> = new EventEmitter<PriceQuote>();

  constructor() { }

  ngOnInit() {
    setInterval(() => {
        const price = Math.random() * 10;
        this.price = price;
        this.lastPrice.emit(new PriceQuote(STOCK_CODE, price));
    }, 1000);
  }

}

export class PriceQuote {
  constructor(public stockCode: string,
              public price: number) {};
}

父组件

import { Component, OnInit } from '@angular/core';
import { PriceQuote } from '../price-quote-inner/price-quote-inner.component';

@Component({
  selector: 'app-price-quote-outer',
  templateUrl: './price-quote-outer.component.html',
  styleUrls: ['./price-quote-outer.component.css']
})
export class PriceQuoteOuterComponent implements OnInit {
  price: number = 0;

  constructor() { }

  ngOnInit() {
  }

  priceChangeHandler(event: PriceQuote) {
      this.price = event.price;
  }


}

 父组件HTML

<app-price-quote-inner (priceChange)="priceChangeHandler($event)"></app-price-quote-inner>
<p>
  Parent component: current priceQuote is {{price | number:"1.2-2"}}
</p>

  

猜你喜欢

转载自www.cnblogs.com/arul/p/10365711.html