Angular ngStyle显示/隐藏条件不起作用

时间:2019-01-25 17:47:19

标签: angular typescript

我试图在单击图像时显示隐藏导航栏。第一次单击时,它就起作用了,之后就不起作用了。不知道出什么问题了。有任何帮助吗?

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)工具栏应显示的页面加载-如预期显示 enter image description here

2)单击图标(在左上角),工具栏应隐藏-首次使用 enter image description here

3)再次单击该图标,工具栏应再次显示-它不起作用

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

3 个答案:

答案 0 :(得分:1)

与其使用1和0进行切换,不如尝试使用true或false,如下所示,它将简化代码并更快地渲染

  

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'}">

答案 1 :(得分:0)

更改

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

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

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

将toggleNavbar功能更改为

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

StackBlitz Link

答案 2 :(得分:0)

向您的打字稿文件添加一个属性,该属性包含如下所示的逻辑:

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

然后,您可以将* ngIf与该属性一起使用以显示或隐藏元素。