How hide and show in angular 4.0

六眼飞鱼酱① 提交于 2019-12-10 14:55:23

问题


I am trying to toggle menu in angular 4. I have 2 separate components. One is for header layout and second one is for menu list. I have written toggle function on click of icon in the header layout and I am trying to hide and show the menu list. But this is not working for me.

Following are my code:

app.navbarComponent.html file:

<header id='sv_header'>
  <div class='row'>
    <div class='col-lg-4 col-md-4 col-sm-4 col-xs-4 col'>
      <a href='' class='logo'>
        <img src='{{ logo }}' alt='Savaari' />
      </a>
    </div>
    <div class='col-lg-4 col-md-4 col-sm-4 col-xs-4 col supportHolder'>
        <img src='{{ customercare }}' alt='24X7 Customer Care Support' />
    </div>
    <div class='col-lg-4 col-md-4 col-sm-4 col-xs-4 text-right col loginHolder'>
      <a class='user_login' (click)='toggleMenu()'>
        <img src='{{ signin }} ' alt='signin' />
        <span>Sign In</span>
      </a>
    </div>
  </div>
</header>

app.navbarComponent.ts file:

import { Component } from '@angular/core';
@Component({
    selector: 'navbar',
    templateUrl: './app.navbarComponent.html'
})
export class NavbarComponent {
    menulist: boolean = false;
    logo = '../assets/img/logo.png';
    customercare = '../assets/img/cc-support.png';
    signin = '../assets/img/signin.png';
    toggleMenu(): void { 
        this.menulist = !this.menulist;
        alert(this.menulist);
    }
}

app.menuComponent.html file:

<div class='menulist'  >
  <ul>
    <li *ngFor="let menu of menus" [HIDDEN]="!menulist">
      <a href="{{menu.href}}">
        {{menu.name}}
      </a>
    </li>
  </ul>
</div>

Can anyone help me to resolve this.

Thanks in advance.


回答1:


<div class='menulist'>
  <ul *ngIf="!menulist">
    <li *ngFor="let menu of menus">
      <a href="{{menu.href}}">
        {{menu.name}}
      </a>
    </li>
  </ul>
</div>

You can't put *ngIf and *ngFor on the same element - angular does not like it




回答2:


It seems to me the right answer is not correct. Angular has two ways to hide data: *ngIf and [hidden].
*ngIf is a structural directive, it creates/destroys content inside the DOM.
[hidden] just hides/shows the content with css (adding/removing display:none to the element's style).
*ngIf redraws DOM, which affects the performance of your project. In this case I advise to use [hidden], because you often manipulate the DOM




回答3:


Issue fixed.

Since we were using the two different component. We have to write a service to listen the click event.

First we have to Bind the click event to the INJECTOR which is called as Service in the angular. After that using the Injector help we are going to call a function in the other component when ever icon is clicked.



来源:https://stackoverflow.com/questions/42897383/how-hide-and-show-in-angular-4-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!