0%

angular-ngIf

Introduction

ngIf is a structural directive in Angular, it is used to conditionally render content in a template. Remember to import CommonModule in the module where you want to use ngIf.

Full syntax with ng-template

Structural directives are used in ng-template, here is an example:

1
2
3
<ng-template [ngIf]="hero">
<div class="name">{{hero.name}}</div>
</ng-template>

Shorthand syntax

But, in practice, we often use ngIf in a more concise way by prefix a * before it, this is called the shorthand syntax:

1
<div *ngIf="hero" class="name">{{hero.name}}</div>

Note, even we write it in the shorthand syntax, Angular will still convert it to the ng-template syntax after compiling.

The above template will create a div element in the template, What if you don’t want to create a div element? You can use ng-container instead of div:

1
2
3
<ng-container *ngIf="condition">
Content to render when condition is true
</ng-container>

In this way, Angular will render the text directly without creating a div element.

New syntax with @if

With the new built-in structural @if directive, you can use the following syntax:

1
2
3
@if (condition) {
Content to render when condition is true
}

If else then with *ngIf

1
2
3
4
5
6
7
8
9
10
<div class="case-3">
<ng-container *ngIf="condition; then thenBlock else elseBlock">
</ng-container>
<ng-template #thenBlock>
Content to render when condition is true
</ng-template>
<ng-template #elseBlock>
Content to render when condition is false
</ng-template>
</div>

If else then with @if

With @if directive, you can use the following syntax, it’s more simple and readable:

1
2
3
4
5
6
7
<div class="case-3">
@if (condition) {
Content to render when condition is true
} else {
Content to render when condition is false
}
</div>

Conclusion

既然Angular已经有ngIf, ngFor, ngSwitch等内置的结构性指令,为什么还要引入新的@if@for, @switch呢?主要有以下原因

  1. 更简洁的语法,比如要实现if - else if - … - else的逻辑,使用ngIf就会显得很臃肿。而使用@if就可以很好的解决这个问题。
  2. 更好的类型检查机制,这个不知道是怎么实现的。
  3. 更好的运行时性能,Angular编译器会将@if@for@switch编译成更高效的代码,这样可以减少运行时的开销。
  4. 更小的包体积,最多可以减少30kb的包体积。
  5. 不需要额外导入CommonModule模块,直接使用即可,ngIf等指令则需要导入CommonModule模块。