Search code examples
javascriptangularng-class

Angular 6 [ngClass] not working with boolean in component.js


What I'm trying to do is hide text when ngState is true. When a certain element is clicked, that state is set to true. The [ngClass] should then add the hide class and hide the text. This first snippet is from the component.ts which outlines the boolean variable and the function which sets it to true.

export class MainMenuComponent implements OnInit {
  ngState = false;
    constructor() {

  }
  newGame(){
    this.ngState = this.ngState === true ? false : true;
    console.log(this.ngState);
  }
}

This next snippet is the component html

<canvas id='sparkCanvas'></canvas>
<div class="menuBox">
    <div class="title" [ngClass]="{'hide': ngState}">Dark Shards</div>
    <div class="optContainer">
        <ul>
            <li *ngFor="let opt of opts" class="{{opt.class}}" [ngClass]="{'hide': ngState}"  (click)="opt.f()">{{opt.n}}</li>
        </ul>
    </div>
</div>

and here is the hide class below

.hide{
  opacity: 0;
}

When I replace [ngClass]="{'hide': ngState}" with [ngClass]="{'hide': true}"

It will then work as intended. What am I not understanding here?

Here is a link to my code with a working example: https://stackblitz.com/edit/angular-fg48ro?file=src%2Findex.html


Solution

  • Try without Quote

      <li *ngFor="let opt of opts" class="{{opt.class}}" [ngClass]="{hide: ngState}"  (click)="opt.f()">{{opt.n}}</li>
    

    EDIT

    When i see your code, the issue is not related to angular, but with javascript context, you need to specifiy the context of this like

    ' f: this.newGame.bind(this),'

    DEMO