Angular

*ngIf

Ngọc Tiên
13
*ngIf

Để làm được như như React

isShow && <Component />
// or
hasDownload ? <ComponentA /> : <ComponentB />

Thì Angular sử dụng cú pháp *ngIf . Cách sử dụng như sau:

<p *ngIf="user.age > 18; else restrictContent">
  You're able to see this content
</p>

<ng-template #restrictContent>
  <p>You're not old enough to see this content</p>
</ng-template>

<button (click)="user.age = user.age - 2">Decrease!</button>

ng-template là một Template chứa các Component hoặc Element đã có sẵn, dùng code để hiển thị ra

<aside> 💡 *ngIf là một Structural Directive, vì nó gỡ bỏ Element/Component ra khỏi DOM

</aside>

Nên kết hợp nó với ng-container thay vì ng-template

Ref: https://viblo.asia/p/tim-hieu-co-ban-ve-directives-trong-angular-ByEZk2roKQ0