Angular中的输入输出是通过注解
输入输出针对的对象是父子组件。
@Input和@Output来标识,它位于组件控制器的属性上方。输入输出针对的对象是父子组件。
@Input和@Output这两个要结合父组件与子组件来说@Input 是 属相绑定,父组件向子组件传递数据
@Output是 事件绑定,子组件向父组件传递数据同时触发事件
child.component.html
<div> <p>宠物名称:{{stockName}}</p> <p>当前价格:{{stockPrice | number:'2.1-2'}}</p></div>child.component.tsimport {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; }}