[英]How to render component with *ngIf else
I am new to angular and I am writing dummy app to teach myself angular. 我是棱角分明的新手,我正在编写虚拟应用来教我自己的棱角分明。 My idea was to have 2 inputs where player1 and player2 write down their names. 我的想法是有2个输入,其中player1和player2记下他们的名字。 When they press the button game starts and shows their names and health. 当他们按下按钮游戏开始并显示他们的名字和健康。
I am doing that with *ngIf else, but when I click the button to change boolean nothing is shown. 我正在使用* ngIf else,但是当我单击按钮更改布尔时,没有显示任何内容。
What is the problem and is there a better way to do that? 有什么问题,还有更好的方法吗?
app.component.html 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 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;
}
}
I want to render other component or HTML if boolean changes in if statment. 我想渲染其他组件或HTML,如果布尔值更改if statment。
The ng-template
just create a template and which won't show by default, use ng-container
for that purpose which helps to group and add multiple elements to DOM. 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>
You can event use *ngIf
directive with the p
tag since there is only one element( p
tag) and use ng-container
whenever you want to group multiple elements. 你可以使用事件*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>
更改* ngIf并写入[ngIf]但不建议使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.