应用场景:搜索组件,购物车组件,主组件充当中间人
(1)股票搜索组件中,发射一个EventEmitter 类型的事件addCart,并将股票信息也发射出去
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-search-stock',
templateUrl: './search-stock.component.html',
styleUrls: ['./search-stock.component.css']
})
export class SearchStockComponent implements OnInit {
@Input()
private keyword:string;
private price :number;
@Output() //searchResult属性是输出属性,输出的是一个事件,事件的类型为EventEmitter
searchResult:EventEmitter<StockInfo>=new EventEmitter();
@Output()
addCart:EventEmitter<StockInfo>=new EventEmitter();
constructor() { }
ngOnInit() {
setInterval(()=>{
let stockInfo:StockInfo=new StockInfo(this.keyword,Math.random()*100);
this.price=stockInfo.price;
this.searchResult.emit(stockInfo);
},3000)
}
buyStock(){
this.addCart.emit(new StockInfo(this.keyword,this.price))
}
}
export class StockInfo{
constructor(public name:string,public price:number){}
}
(2)中间人组件,在主组件中捕获股票搜索组件发射的事件和信息,然后将拿到的信息再传给购物车组件
<input [(ngModel)]="search" />
<app-search-stock [keyword]="search" (addCart)="addcartHandler($event)"></app-search-stock>
<app-cart [stockInfo]="stockInfo"></app-cart>
在控制器
export class AppComponent {
public stockInfo:StockInfo;
addcartHandler(StockInfo){
this.stockInfo=StockInfo;
}
}
(3)购物车组件,接收从父组件传递过来的股票信息
import { Component, OnInit, Input } from '@angular/core';
import { StockInfo } from '../search-stock/search-stock.component';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
constructor() { }
//购物车组件通过stockInfo这个输入属性,来知道要购买的股票信息
@Input() private stockInfo:StockInfo;
ngOnInit() {
}
}
模板:
<p>
我是购物车
要购买的股票是{{stockInfo.name}},价格是{{stockInfo.price}}
</p>