Skip to content

Angular, Directive *ngIf

2017-11-13 02:00:57

Simple example of ngIf directive that is part of Angular core. Everything what you need will be generated after executing this command ng g c post. After that, what you have to do, is adjust few files. Of course more you can find in Angular documentation, here is only my note. One more thing, if you don't like to install node mess on your local computer you can use my or similar docker image

Create new component

ng g c post


  create src/app/post/post.component.css (0 bytes)
  create src/app/post/post.component.html (23 bytes)
  create src/app/post/post.component.spec.ts (614 bytes)
  create src/app/post/post.component.ts (321 bytes)
  update src/app/app.module.ts (1265 bytes)


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

  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css'],
  encapsulation: ViewEncapsulation.None
export class PostComponent {

  type: string

post.component.html (version 1)

<h1 &quot;="" *ngif='"type' =="POS">Post</h1>
<h1 &quot;="" *ngif='"type' =="ART">Article</h1>

post.component.html (version 2)

<span *ngif='"type' ;="" =="POS" article&quot;="" else="" post="" then=""></span>
<ng-template #post=""><h1>Post</h1></ng-template>
<ng-template #article=""><h1>Article</h1></ng-template>


<app-post [type]="&quot;'POS'&quot;"></app-post>

<app-post [type]="&quot;'ART'&quot;"></app-post>