我无法在我的 Angular 5 应用程序中让 ngClass 工作,无论我用来有条件地显示它的布尔变量是真还是假,该类总是显示。
我有一个显示评级星星的组件:
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);
}
}
这是我的网页
<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 中,那么它会正确反映,根据我如何调用它显示真或假。 我像这样调用该组件:
<rating-star max=5 readOnly="true" initial=4></rating-star>
但是,我的 hideme 类总是被添加到组件中。 我做错了什么。
这
背后的原因是,您的
hideHover
值总是转换为string
,不进入Boolean
,因为你的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>