0

I am very new at angular and I tried to learn angular 5 from basic. I just tried the ngIf directive and I found that if part has not got any problem but when I use else part as in the following code the error saying is not a known element. I think there is something wrong in the else part. Help me.

now I edited the quote and it still sends the same error. Is there something I'm missing. I'm very new to angular.

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-test',
      template: `
        <h2 *ngIf = "isVisible; else elseBlock" >
            This is visible
        </h2>
        <ng-template #elseBlock>
          <h2>
              This is not visible.
          </h2>
        </ng-template>
      ` ,
      styles: []
    })

    export class TestComponent implements OnInit {
      public name = "Dipesh";
      public isVisible = true;
      constructor() { }
      ngOnInit() {
      }
    }
dipesh
  • 763
  • 2
  • 9
  • 27

3 Answers3

2
*ngIf = "isVisible"; else elseBlock

should be

*ngIf = "isVisible; else elseBlock"

You had the closing " in the wrong place ending the *ngIf prematurely.

Igor
  • 60,821
  • 10
  • 100
  • 175
  • @DipeshPaudel - it does work. See this [stackblitz](https://stackblitz.com/edit/angular-tqjfm7). Your only problem was the one I corrected above in my answer. – Igor Apr 17 '18 at 16:28
0

i think the problem is missing quote

 @Component({

  selector: 'my-app',
  template: `
    <div>
        <h2 *ngIf="isVisible; else elseBlock">
            This is visible
        </h2>
        <ng-template #elseBlock>
          <h2>
              This is not visible.
          </h2>
        </ng-template>
    </div>
  `,
})
export class App {
  name:string;
  isVisible:boolean;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
    this.isVisible=true;
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
happyZZR1400
  • 2,387
  • 3
  • 25
  • 43
0

Look at the example from angular.io docs: https://angular.io/api/common/NgIf

@Component({
  selector: 'ng-if-else',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show; else elseBlock">Text to show</div>
    <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
class NgIfElse {
  show: boolean = true;
}

Like @Joe Clay said, you have to putting your else inside the quotes.

Maicon Heck
  • 2,017
  • 1
  • 20
  • 27