6

The 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, the browser console errors: "Can't bind to 'ngIfElse' since it isn't a known property of 'div'."

My module looks like this (I am 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 issue is? If I simply remove the "; else elseBlock" from the div, the *ngIf statement works as intended. Therefore, I believe my imports are correct. Any help is greatly appreciated.

rhino5oh
  • 1,404
  • 1
  • 11
  • 8
  • 1
    Which version angular are you using? Import `CommonModule` is reduntant in your case – yurzui Jan 29 '17 at 19:47
  • 3
    `ngIfElse` input was introduced since angular **4.0.0-beta.0** – yurzui Jan 29 '17 at 19:52
  • I'm just beginning to learn Angular and started with the quickstart seed project. Looking at my package.json, I believe I'm using 2.4.0 for most things: "dependencies": { "@angular/common": "~2.4.0", "@angular/compiler": "~2.4.0", "@angular/core": "~2.4.0", "@angular/forms": "~2.4.0", "@angular/http": "~2.4.0", "@angular/platform-browser": "~2.4.0", "@angular/platform-browser-dynamic": "~2.4.0", "@angular/router": "~3.4.0", – rhino5oh Jan 29 '17 at 20:08
  • can you show us how your component look like ? – mickdev Jan 29 '17 at 22:15
  • @mickdev please see the answer that I posted. Looks like the 'else' portion wasn't working until 4.0.0-beta.0 – rhino5oh Jan 29 '17 at 22:50

2 Answers2

2

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 changelog (https://github.com/angular/angular/blob/master/CHANGELOG.md) it appears that the 'else' portion of ngIf did not even work until angular 4.0.0-beta.0

I am unsure why the official documentation explains how to use 'else' because, at of the time of this writing, the latest stable version doesnt even support the 'else' portion of *ngIf

rhino5oh
  • 1,404
  • 1
  • 11
  • 8
0

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 the angular version from 2 to 4, rest is all fine

VIKAS KOHLI
  • 8,164
  • 4
  • 50
  • 61