Angular, Directive *ngIf


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
https://hub.docker.com/r/szalek/angular-cli/

Create new component

ng g c post

Output

  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)

post.component.ts

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

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

  @Input()
  type: string
}

post.component.html (version 1)

<section>
  <h1 *ngIf="type == 'POS'">Post</h1>
  <h1 *ngIf="type == 'ART'">Article</h1>
</section>

post.component.html (version 2)

<section>

  <span *ngIf="type == 'POS'; then post else article"></span>

  <ng-template #post><h1>Post</h1></ng-template>
  <ng-template #article><h1>Article</h1></ng-template>

</section>

Usage

<app-post [type]="'POS'"></app-post>
<app-post [type]="'ART'"></app-post>