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:

9

1 Answer

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

7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest