如何使用* ngIf else

时间:2019-04-01 13:40:10

标签: javascript angular

我是angular的新手,我正在编写虚拟应用程序以自学。 我的想法是有2个输入,其中player1和player2写下他们的名字。当他们按下按钮时,游戏开始,并显示他们的姓名和健康状况。

我正在使用* ng进行其他操作,但是当我单击按钮以更改布尔值时,什么也没有显示。

问题出在哪里,有没有更好的方法呢?

app.component.html

<p>This will not change!</p>
<ng-template *ngIf="startGame;
  else noStart">
  <p> Render other components for health and names. Did game start: {{startGame}}</p>
</ng-template>
<ng-template #noStart>
  <h1> Input player names to start the game!</h1>
  <input [(ngModel)]="player1">
  <br>
  <input [(ngModel)]="player2">
  <br>
  <button (click)="onStartGame()">Start</button>
</ng-template>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  startGame: boolean = false;
  player1: string = '';
  player2: string = '';
  username = '';

  setPlayer1(event) {
    this.player1 = event.target.value;
  }

  setPlayer2(event) {
    this.player2 = event.target.value;
  }

  onStartGame() {
    if(this.player1 !== '' && this.player2 !== '')
      this.startGame = true;
  }
}

如果语句中的布尔值更改,我想呈现其他组件或HTML。

2 个答案:

答案 0 :(得分:4)

ng-template仅创建一个模板,默认情况下不会显示,为此使用ng-container有助于分组和  向DOM中添加多个元素。

<p>This will not change!</p>
<ng-container *ngIf="startGame;
  else noStart">
  <p> Render other components for health and names. Did game start: {{startGame}}</p>
</ng-container>
<ng-template #noStart>
  <h1> Input player names to start the game!</h1>
  <input [(ngModel)]="player1">
  <br>
  <input [(ngModel)]="player2">
  <br>
  <button (click)="onStartGame()">Start</button>
</ng-template>

您可以将*ngIf指令与p标记一起使用,因为只有一个元素(p标记),并且每当您要对多个元素进行分组时都可以使用ng-container

<p>This will not change!</p>
<p *ngIf="startGame;
  else noStart"> Render other components for health and names. Did game start: {{startGame}}</p>
<ng-template #noStart>
  <h1> Input player names to start the game!</h1>
  <input [(ngModel)]="player1">
  <br>
  <input [(ngModel)]="player2">
  <br>
  <button (click)="onStartGame()">Start</button>
</ng-template>

答案 1 :(得分:-1)

更改* ngIf并输入[ngIf],但不推荐