简体   繁体   中英

ngClass always showing the class regardless of boolean in Angular 5

I can't get ngClass working in my Angular 5 app, the class is always showing regardless of if the boolean variable that I am using to show it conditionally is true or false.

I have a component that shows rating stars:

    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);
        }

    }

This is my 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>

If I add {{this.hideHover}} to this html then it is reflecting properly, showing true or false depending on how I call it. I call the component like so:

<rating-star max=5 readOnly="true" initial=4></rating-star>

However my hideme class is always being added to the component. What am I doing wrong.

Reason behind this is , your hideHover value is always converted to string , not into Boolean , coz of that your hideme class is always added no matter it is false or true ,

<div [ngClass]="{ 'hideme': this.hideHover == 'true' }">

OR

this.hideHover = this.readOnly && this.readOnly == 'true' ? true : false;

To Check that add this component side

ngOnChanges(){
    console.log(typeof this.readOnly) // this will output the string not boolean
}

WORKING DEMO

尝试这个

<rating-star max=5 readOnly="'true'" initial=4></rating-star>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM