![](/img/trans.png)
[英]Angular2,How to broadcast event from parent component to child directive?
[英]angular2 child component does not load on subsequent event fired from parent component
我有一個父組件Home和一個子組件Hall 。 從主頁我選擇一個城市,並根據選擇的城市,我想從我的霍爾元件加載所有的“殿堂”。
原始HTML:
<div class="dropdown">
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Select your city</button>
<div class="dropdown-content">
<ul *ngFor = "let city of cities">
<a (click)="selectCity(city)" > {{city.name}} </a>
</ul>
</div>
<hall *ngIf = "isSelectHall" [city]="specific_city" ></hall>
</div>
家庭組件:
constructor(private homeService: HomeService) {
}
ngOnInit() {
this.homeService.getCities().then (
data => {
this.cities = data;
});
}
selectCity(city:any) {
this.specific_city = city;
this.isSelectHall = true;
}
霍爾組件:
export class Hall implements OnInit{
@Input() city: any;
halls: Object;
openDiv : boolean;
specific_hall: Object;
cart : any;
cartCount: number;
cartHalls: any;
countHall: number;
constructor(private hallService: HallService){
this.cart=[];
}
ngOnInit(){
this.fetchData(this.city.id)
}
fetchData(cityId : any) {
this.hallService.fetchData(cityId)
.then(
data => {
this.halls = data;
});
}
clicked(item : any) {
this.specific_hall = item
}
onNotify(cartItems : any) : void {
this.cartHalls = cartItems;
this.cartCount = this.cartHalls.length;
}
}
大廳HTML:
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--4-col">
<div class="populate-table" [hidden]="!halls">
<table>
<tr>
<th>Name</th>
<th>Landmarks</th>
<th>Seating capacity</th>
<th>Details</th>
</tr>
<tr *ngFor="let item of halls">
<td> {{ item.name }} </td>
<td> {{ item.landmarks }} </td>
<td> {{ item.seating_capacity }} </td>
<td> <a (click)="clicked(item)"> See </a> </td>
</tr>
</table>
</div>
</div>
我面臨的問題是:第一次單擊Home中的 selectCity(city)
,它將加載特定於所選城市的所有大廳,但是當我隨后單擊任何其他城市時,它沒有任何作用。 我在這里做錯了什么?
Scrrenshot :
您需要設置一個觸發器以在子級中重新運行fetchData方法; 類似於onChanges或與子組件通信(請參見下文)。 ngInit將一次運行,但不會在每次組件屬性發生更改時再次運行。 這是帶有獲取/設置父/子通訊方式的代碼示例。
父/子組件交互: https : //angular.io/docs/ts/latest/cookbook/component-communication.html#!# parent-to-child
private this._city: Object;
@Input ()
set city(city: Object) {
this._city = city;
this.fetchData(this.city.id);
//whenever city changes via Input, halls is updated which will cause *ngFor to re-render)
}
get city() {
return this._city;
}
將設置器添加到您的輸入中,如https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter中所述,並從中觸發對fetchData的調用。 應該看起來像這樣(未經測試):
export class Hall implements OnInit{
private _city: any = {};
@Input()
set city(city: any) {
this._city = city;
this.fetchData(this.city.id);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.