SK.
SK.

Reputation: 1510

Angular ngStyle show/hide condition not working

I am trying to show hide my navbar on click of an image. On first click it is working, after that it doesn't. Not sure what is wrong. Any help please???

https://stackblitz.com/edit/responsive-menu-angular-material-flex-layout-cm87il

<img id="project-avatar" (click)="toggleNavbar()" width=20, height=20 style="position: relative;" alt="Show Hide Navigation Menu" src="/assets/img/slider_hide.png" />
<div> 

<div class="showHideNavbar" [ngStyle]="displayNavbar == '1' ? {'visibility': 'visible'} : {'visibility': 'hidden'}">
  <mat-toolbar color="primary" >

component.ts

displayNavbar: string;

ngOnInit() {
    this.displayNavbar = '1';
}

toggleNavbar() {

    if(this.displayNavbar == '0') {
        this.displayNavbar = '1';
        alert(this.displayNavbar);
    } if(this.displayNavbar == '1') {
    //    alert("1 - Changing to 0");
        this.displayNavbar = '0';
    } else {
        this.displayNavbar = '1';
    }
}

1) Onload of the page the toolbar should show - it is showing as expected enter image description here

2) On click of the icon(at top left corner), the toolbar should hide - it is working first time enter image description here

3) On click of the icon again, the toolbar should display again - it is NOT working

https://stackblitz.com/edit/responsive-menu-angular-material-flex-layout-cm87il

Upvotes: 3

Views: 10666

Answers (3)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30625

change

 [ngStyle]="displayNavbar == '1' ? {'visibility': 'visible'} : {'visibility': 'hidden'}"

to

 [ngStyle]="{'visibility': displayNavbar == '1' ? 'visible' : 'hidden'}"

or

[style.visibility]="displayNavbar == '1' ? 'visible' : 'hidden'"

change toggleNavbar function to

toggleNavbar() {
   this.displayNavbar = (this.displayNavbar == '1') ? '0' : '1'
}

StackBlitz Link

Upvotes: 7

amul klinton
amul klinton

Reputation: 51

Instead of using 1 and 0 to toggle , try using true or false like the following which will simplify code and render faster

Component.ts

 displayNavbar: string;ngOnInit() {
    this.displayNavbar = false; // on init based on the logic set it to true or false
}

toggleNavbar() {
this.displayNavbar = ! this.displayNavbar; //toggle between true or false dynamically
}

html

  <img id="project-avatar" (click)="toggleNavbar()" width=20, height=20 style="position: relative;" alt="Show Hide Navigation Menu" src="/assets/img/slider_hide.png" />
<div> 

<div class="showHideNavbar" [ngStyle]="(displayNavbar) ? {'visibility': 'visible'} : {'visibility': 'hidden'}">

Upvotes: 2

dmoore1181
dmoore1181

Reputation: 2102

Add a property to your typescript file that holds the logic something like the following:

get showNavBar(): boolean {
    return this.displayNavBar === 1;
 }

Then you can use an *ngIf with that property to show or hide an element.

Upvotes: 1

Related Questions