Javascript 将*ngIf与else一起使用时出错

Javascript 将*ngIf与else一起使用时出错,javascript,angular,angular-ng-if,Javascript,Angular,Angular Ng If,这是我的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';

这是我的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';

}
这是我的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>

登录成功
登录失败
将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.
错误:src/app/app.component.html:1:56-错误TS2339:类型“AppComponent”上不存在属性“elseBlock”。
1.
~~~~~~~~~
src/app/app.component.ts:5:16
5 templateUrl:“./app.component.html”,
~~~~~~~~~~~~~~~~~~~~~~
组件AppComponent的模板中发生错误。

您的elseBlock不能位于*ngIf管理的块内。 正确的模板应如下所示:

<div *ngIf="username=='root' && password=='root'; else elseBlock">

  <h3>Login suceess</h3>


</div>
<ng-template #elseBlock>
  <h3>Login failed</h3>
</ng-template>

登录成功
登录失败

您甚至不需要ngIf。您可以使用三元运算符进行求解:

<h3> 
  {{ ((username === 'root') && (password === 'root')) ? 'Login success' : 'Login failed'
</h3>

{((用户名=='root')&&(密码=='root')?“登录成功”:“登录失败”