[英]ngClass always showing the class regardless of boolean in Angular 5
我無法在Angular 5應用程序中使用ngClass,無論我用來有條件地顯示它的布爾變量是true還是false,該類始終顯示。
我有一個顯示星級的組件:
export class RatingStarComponent {
@Input() max: number;
@Input() initial: number;
@Input() readOnly: boolean;
@Output() onRating = new EventEmitter<Number>();
maxItem: any[];
ratedCount: number;
hideHover: boolean;
constructor() {}
ngOnInit() {
this.ratedCount = this.initial;
this.hideHover = this.readOnly;
this.maxItem = [];
for (var i = 0; i < this.max; i++) {
this.maxItem.push(i + 1);
}
}
toggleRating(s: number) {
this.ratedCount = s;
this.onRating.emit(this.ratedCount);
}
}
這是我的HTML
<div [ngClass]="{ 'hideme': this.hideHover }">
<span class="icon" *ngFor="let s of maxItem">
<i [ngClass]="s <= this.ratedCount ? 'filled' : ''" class="fa fa-star" aria-hidden="true" (click)="toggleRating(s)"></i>
</span>
</div>
如果我將{{this.hideHover}}添加到此html,則表示它正確反映了,根據我的稱呼顯示為true或false。 我這樣稱呼組件:
<rating-star max=5 readOnly="true" initial=4></rating-star>
但是,我的hideme類始終被添加到組件中。 我究竟做錯了什么。
原因是,您的
hideHover
值始終轉換為string
,而不轉換為Boolean
,因為無論它是false還是true,總是會添加hideme
類,
<div [ngClass]="{ 'hideme': this.hideHover == 'true' }">
要么
this.hideHover = this.readOnly && this.readOnly == 'true' ? true : false;
要檢查是否添加此組件側
ngOnChanges(){
console.log(typeof this.readOnly) // this will output the string not boolean
}
嘗試這個
<rating-star max=5 readOnly="'true'" initial=4></rating-star>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.