簡體   English   中英

在 angular 中將 *ngIf 與 else 一起使用時出現錯誤

[英]Getting error when using *ngIf with else in angular

這是我的 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.

你的 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM