How hide and show in angular 4.0
Solution 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
Solution 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
Pavan Ural
Updated on May 24, 2020Comments
-
Pavan Ural almost 4 years
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.