在Angular中使用ngIf进行条件渲染

时间:2019-11-23 12:25:16

标签: angular typescript

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)我想有条件地呈现代码

2)每当用户单击我要列出的标头组件以单击事件并触发一种方法时,该方法依次更改代码中的bollenType并导出为输出

3)反过来,我要列出该表达式,以便列出

但是我的代码无法正常工作,我不知道为什么

2 个答案:

答案 0 :(得分:0)

似乎不需要声明为Output属性:

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

,因为它们仅用作变量。因此更改为:

receipeClick = true;
shoppingClick = true;

答案 1 :(得分:0)

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;
  }