組件通信
<app-stars [roting]="product.stars"></app-stars>
import {Component, Input} from "@angular/core";
@Component({
selector: 'app-stars',
templateUrl: './stars.component.html',
styleUrls: ['./stars.component.css']
})
export class StarsComponent implements OnInit, OnChanges {
@input()
private roting:number=0;
constructor() {
}
}
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'my-voter',
template: `
<h4>{{name}}</h4>
<button (click)="vote(true)">Agree</button>
`
})
export class VoterComponent {
@Output() onVoted = new EventEmitter<boolean>();
vote(agreed: boolean) {
this.onVoted.emit(agreed);
}
}
import { Component } from '@angular/core';
@Component({
selector: 'vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<my-voter *ngFor="let voter of voters"
[name]="voter"
(onVoted)="fnonVoted($event)">
</my-voter>
`
})
export class VoteTakerComponent {
agreed = 0;
disagreed = 0;
voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];
fnonVoted(agreed: boolean) {
agreed ? this.agreed++ : this.disagreed++;
}
}
- 當子組件的屬性既想輸入又想輸出時需要給這個對象進行雙向數據綁定[(name)]=””
- input()name
- onput()nameChange這必須是這個名字
- 中間人模式
<app-price-quote (buy)="buyHandler($event)"></app-price-quote>
<app-order [priceQuote]="priceQuote"></app-order>
export class AppComponent {
priceQuote:PriceQuote = new PriceQuote("", 0);
buyHandler(event: PriceQuote) {
this.priceQuote = event;
}
import {Component, OnInit, EventEmitter, Output} from '@angular/core';
@Component({
selector: 'app-price-quote',
templateUrl: './price-quote.component.html',
styleUrls: ['./price-quote.component.css']
})
export class PriceQuoteComponent implements OnInit {
stockCode:string = "IBM";
price: number;
@Output('priceChange')
lastPrice:EventEmitter<PriceQuote> = new EventEmitter();
@Output()
buy:EventEmitter<PriceQuote> = new EventEmitter();
constructor() {
setInterval(() => {
let priceQuote:PriceQuote = new PriceQuote(this.stockCode, 100*Math.random());
this.price = priceQuote.lastPrice;
this.lastPrice.emit(priceQuote);
}, 1000)
}
buyStock(event) {
this.buy.emit(new PriceQuote(this.stockCode, this.price));
}
ngOnInit() {
}
}
export class PriceQuote {
constructor(public stockCode:string,
public lastPrice:number
){
}
}
}
export class OrderComponent implements OnInit {
@Input()
priceQuote:PriceQuote;
constructor() {
}
}
- @ViewChild():類似的,也可以在腳本中用@ViewChild()來獲取子組件