Search code examples
angularangular-ng-ifangularjs-ng-if

Angular 4+ : Why isn't ng-if working in app.componet.html?


I am currently trying to use an ng-if directive in my app.component.html file:

<p>This should appear.</p>

<p ng-if="0==1">This shouldn't, but it does.</p>

My app.component.ts file looks like this:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
}

I have tried numerous different values instead of 0==1 and it still doesn't work, including using the value of a passed-in variable. It is compiling and displaying without errors, but is not removing the second p.

I have also tried *ng-if. When I do that, I get an error:

Template parse errors:

Can't bind to 'ng-if' since it isn't a known property of 'p'. ("<p>This should appear.</p>

<p [ERROR ->]*ng-if="0==1">This shouldn't, but it does.</p>

"): ng:///AppModule/AppComponent.html@2:3
Property binding ng-if not used by any directive on an embedded template. 
Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("<p>This should appear.</p>

Solution

  • In Angular structural directives are prefixed with an asterisk (*) and the directive is written without the dash. Check the official documentation for details:

    To fix you code write *ngIf instead of ng-if.

    https://angular.io/guide/structural-directives#asterisk

    Quick glimpse why from the official docs:

    The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular translates the *ngIf attribute into a element, wrapped around the host element.