Search code examples
javascriptangularangular-ng-if

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.

Solution

  • 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>