Angular 2 - * ngIf with an else block gives me "Can't bind to" ngIfElse ", but * ngIf without using a block

An example directly from angular.io will not work for me:

<button (click)="show = !show">{{show ? 'hide' : 'show'}}</button> show = {{show}} <br> <div *ngIf="show; else elseBlock">Text to show</div> <template #elseBlock>Alternate text while primary text is hidden</template> 

Instead, an error in the browser console: "You can not bind to" ngIfElse ", as this is not a known property of the" div "."

My module looks like this (including CommonModule):

 import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule, CommonModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } 

So I'm not sure what the problem is? If I just remove the โ€œ; else elseBlockโ€ from the div, the * ngIf operator works as intended. Therefore, I believe that my import is correct. Any help is appreciated.

+5
source share
2 answers

So, I got this to work after changing the angular versions in my package.json file from 2.4.0 to 4.0.0-beta.5. If you look at the angular change log ( https://github.com/angular/angular/blob/master/CHANGELOG.md ), it looks like the 'else' part of ngIf does not work even until angular 4.0.0- beta.0

I'm not sure the official documentation explains how to use "else" because at the time of this writing, the latest stable version does not even support the "else" * ngIf part

+2
source

This will work in Angular 4 version

// Syntax for ngIf / Else

 <div *ngIf="condition; else elseBlock">Truthy condition</div> <template #elseBlock>Falsy condition</template> 

Just upgrade your Angular version from 2 to 4, rest is all right

0
source

Source: https://habr.com/ru/post/1263550/


All Articles