Pavan Ural
Pavan Ural

Reputation: 63

How hide and show in angular 4.0

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.

Upvotes: 6

Views: 25446

Answers (3)

Sergey Andreev
Sergey Andreev

Reputation: 1488

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

Upvotes: 2

Pavan Ural
Pavan Ural

Reputation: 63

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.

Upvotes: 0

IndyWill
IndyWill

Reputation: 2945

<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

Upvotes: 11

Related Questions