[英]Getting error when using *ngIf with else in angular
Here is my app.component.ts file这是我的 app.component.ts 文件
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public title:string = 'angularapp';
public username:string='root';
public password:string='root';
}
Here is my app.component.html这是我的 app.component.html
<div *ngIf="username=='root' && password=='root'; else elseBlock">
<h3>Login suceess</h3>
<ng-template #elseBlock>
<h3>Login failed</h3>
</ng-template>
</div>
I have get an error when add else elseBlock to *ngIf here is the error将 else elseBlock 添加到 *ngIf 时出现错误,这是错误
Error: src/app/app.component.html:1:56 - error TS2339: Property 'elseBlock' does not exist on type 'AppComponent'.
1 <div *ngIf="username=='root' && password=='root'; else elseBlock">
~~~~~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
Your elseBlock cannot be inside the block managed by *ngIf.你的 elseBlock 不能在 *ngIf 管理的块内。 The correct template should look like this:正确的模板应如下所示:
<div *ngIf="username=='root' && password=='root'; else elseBlock">
<h3>Login suceess</h3>
</div>
<ng-template #elseBlock>
<h3>Login failed</h3>
</ng-template>
You need not even have ngIf.你甚至不需要 ngIf。 You can solve it using ternary operators:您可以使用三元运算符解决它:
<h3>
{{ ((username === 'root') && (password === 'root')) ? 'Login success' : 'Login failed'
</h3>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.