我剛剛開始學習Angular,但是我遇到了一個問題,在過去的幾個小時里我一直試圖解決這個問題。我在兩個組件之間有一個父子關系。現在我想把一個boolean變數從我的主人那里分享給一個孩子。當它為真時,子代應該顯示一個文本,如果它為假,則顯示一個不同的文本。下面是@Output的代碼:
import {Component, EventEmitter, OnInit, Output}。from '@angular/core'/span>。
import {Offer}。from "./././models/offer"。
@Component({
selector: 'app-overview2',
templateUrl: './overview2.component.html',
styleUrls: ['./overview2.component.css']
})
export class Overview2Component implements OnInit {
public offers: Offer[] = [] 。
constructor() { }
ngOnInit()。void {
for (let i = 0; i < 8; i ) {
this.addRandomOffer()。
}
}
public addRandomOffer()。void {
let offer = Offer.createRandomOffer() 。
this.offers.push(offer)。
}
public highlightClickedRow(offer :offer) {
for (let i = 0; i < this. offers.length; i ) {
if (this.offers[i] != offer) {
this.offers[i].rowClicked = false;
}
else {
this.offers[i].rowClicked = true;
this.selected.emit(true)。
}
}
}
@Output('update' )
selected: EventEmitter<boolean> = new EventEmitter<boolean>()。
}
然后在我的父節點的HTML中,我有以下內容:
<div>
<app-detail2 [offerSelected]="selected"/span>> </app-detail2>>
</div>/span>
在子程式的TypeScript中,我收集了@Output,如下所示:
({
selector: 'app-detail2',
templateUrl: './detail2.component.html',
styleUrls: ['./detail2.component.css']
})
export class Detail2Component implements OnInit {
() offerSelected: EventEmitter<boolean> = new EventEmitter<boolean>()。
constructor() {
}
ngOnInit()。void {
}
然后在子HTML中,我想使用布林值來決定是否顯示一個標簽,使用的代碼如下:
<div *ngIf="offerSelected. prototype then thenBlock else elseBlock"></div>
<br>/span>
{{offerSelected.prototype}}
<ng-template #thenBlock>< label id="lblSomethingSelected"/span>> Something has been selected yet</label></ng-template>
<ng-template #elseBlock><。 label id="lblNothingSelected"/span>> 尚未選擇任何東西</label></ng-template>
但我遇到的問題是,offerSelected總是false。現在我認為這是因為offerSelected的型別是EventEmitter<boolean>,而不是一個真正的boolean。但是我怎樣才能像我想的那樣使用它呢?請讓我知道!
uj5u.com熱心網友回復:
只是為了在答案中捕捉討論的內容......
當你在組件之間有一個父子關系,并將資料從父方傳遞給子方時,你不需要EventEmitter。你只需要在父類上設定一個屬性,然后指定一個@Input來接收子類中的值。
/ parent.component.ts
選定。boolean。
// child.component.ts
@Input()
offerSelected: boolean。
有了這樣的改變,孩子中的HTML可以是:
< div *ngIf="offerSelected then thenBlock else elseBlock"></div>
<ng-template #thenBlock>
<label id="lblSomethingSelected"/span>> 某物已被選中</label>。
</ng-template>/span>
<ng-template #elseBlock>/span>
<label id="lblNothingSelected"/span>> 尚未選擇任何東西</label>。
</ng-template>/span>
如果你要將資料從子節點發送到父節點,那么你需要一個EventEmitter。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321625.html
標籤:
上一篇:次級集合的總和
下一篇:為什么Chrome和Firefox的<inputtype="date">在en-GB語言環境中使用mm/dd/yyyy格式?
