Reputation: 1510
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" >
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
2) On click of the icon(at top left corner), the toolbar should hide - it is working first time
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
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'
}
Upvotes: 7
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
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