angular input和output

昔憶落落發表於2019-03-11
Angular中的輸入輸出是通過註解@Input@Output來標識,它位於元件控制器的屬性上方。
輸入輸出針對的物件是父子元件。

@Input和@Output這兩個要結合父元件與子元件來說

@Input 是 屬相繫結,父元件向子元件傳遞資料

@Output是 事件繫結,子元件向父元件傳遞資料同時觸發事件




child.component.html

<div>  <p>寵物名稱:{{stockName}}</p>  <p>當前價格:{{stockPrice | number:'2.1-2'}}</p></div>複製程式碼
child.component.ts複製程式碼

import {Component, OnInit, Input, EventEmitter, Output} from '@angular/core';import {StockInfo} from '../models/stockInfo';
@Component({  selector: 'app-child',  templateUrl: './child.component.html',  styleUrls: [ './child.component.scss' ]})export class ChildComponent implements OnInit {
  @Input()  stockName: string;  stockPrice: number;
  @Output()  event: EventEmitter<StockInfo> = new EventEmitter();
  constructor() {  }
  ngOnInit() {    setInterval(() => {      const stock: StockInfo = new StockInfo(this.stockName, 100 * Math.random());      this.stockPrice = stock.price;      this.event.emit(stock);    }, 3000);  }}複製程式碼

stockInfo.ts

export class StockInfo {    constructor(        public name: string,        public price: number    ) {        this.name = name;        this.price = price;    }}複製程式碼

parent.component.html

<input placeholder="請輸入寵物名稱" [(ngModel)]="keyWord"><div>  <p>寵物名稱:{{keyWord}}</p>  <p>當前價格:{{currentPrice | number:'2.1-2'}}</p></div><hr><app-child [stockName]="keyWord" (event)="eventHandler($event)"></app-child>複製程式碼

parent.component.ts

import {StockInfo} from '../models/stockInfo';

export class ParentComponent implements OnInit {  keyWord: string;  currentPrice: number;  eventHandler(stock: StockInfo) {    this.currentPrice = stock.price;  }}複製程式碼


相關文章