简体   繁体   中英

conditional rendering using ngIf in Angular

header.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a href="#" class="navbar-brand">Recipe Book</a>
    </div>

    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li><a href="#" (click)="onReceipeList()">Recipes</a></li>
        <li><a href="#" (click)="onShoppingList()">Shopping List</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" role="button">Manage <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Save Data</a></li>
            <li><a href="#">Fetch Data</a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav>

header.component.ts

import { Component, Output } from '@angular/core';
import { EventEmitter } from 'events';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html'
})


export class HeaderComponent {
  // now call the methods 
  @Output()receipeClick=true;
  @Output()shoppingClick=true;

  onReceipeList(){
    console.log("we are inside Receipe List")
    this.receipeClick=false;
  }

  onShoppingList(){
    console.log("we are inside shooping click")
    this.shoppingClick=false;
  }
}

app-component.html

<app-header></app-header>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <app-recipes *ngIf="!receipeClick"></app-recipes>
      <app-shopping-list *ngIf="!shoppingClick"></app-shopping-list>
    </div>
  </div>
</div>

1)i want to render my code conditionally

2)Whenever the user click the header component i am listing to click event and trigring a method which inturn changing the bollenType in my code and exporting as output

3)Inturn i am listing to that expression so the list

but my code is not working i don't know why

It looks like there is no need to declare as Output properties:

@Output()receipeClick=true;
@Output()shoppingClick=true;

as they are used just as variables. So change to:

receipeClick = true;
shoppingClick = true;

app.component.html

<app-header (receipeClick)="updatereceipeClick($event)" (shoppingClick)="updatereceipeClick($event)">
</app-header>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <app-recipes *ngIf="!receipeClick"></app-recipes>
      <app-shopping-list *ngIf="!shoppingClick"></app-shopping-list>
    </div>
  </div>
</div>

app.component.ts

receipeClick = true;
shoppingClick = true;

updatereceipeClick(val) {
    this.receipeClick = val;
  }
updateshoppingClick(val) {
    this.shoppingClick = val;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM