简体   繁体   中英

Getting error when using *ngIf with else in angular

Here is my app.component.ts file

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

<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

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. 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. You can solve it using ternary operators:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM