@Input
和
@Output
來標識,它位於組件控制器的屬性上方。
@Input和@Output這兩個要結合父組件與子組件來講@Input 是 屬相綁定,父組件向子組件傳遞數據css
@Output是 事件綁定,子組件向父組件傳遞數據同時觸發事件html
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.tsbash
export class StockInfo { constructor( public name: string, public price: number ) { this.name = name; this.price = price; }}複製代碼
<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
app
import {StockInfo} from '../models/stockInfo';
export class ParentComponent implements OnInit { keyWord: string; currentPrice: number; eventHandler(stock: StockInfo) { this.currentPrice = stock.price; }}複製代碼