Search code examples
angularangular-ng-if

Hide and show element based on value Angular 2


I have some variable that is a boolean and can be true or false, based on that value I have to show some element in HTML like this:

<p *ngif=isOwner>Test</p>

The problem is I have that I have to hide that element is value is false but to show element is value is true:

this.storage.get('User').then((val) => {
    this.isOwner = val.Owner.IsOwner;
});

What will be the proper way to do that in Angular 2, just within HTML, value will always be there, and will be true or false?


Solution

  • Just inverse the boolean value of the condition:

    See live stackblitz

    export class AppComponent  {
      public isOwner: boolean = true;
      toggleIsOwner() {
        this.isOwner = !this.isOwner; 
      }
    }
    

    HTML

    <button (click)="toggleIsOwner()">show/hide</button>
    
    <p *ngIf="isOwner">Hello World!</p>
    

    showMe is a boolean. The way *ngIf works is that when the expression is true, the element is inserted in the DOM, when the expression is false, the element is removed from the DOM.