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 | <ng-template [ngIf]="hero"> |
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 | <ng-container *ngIf="condition"> |
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 | @if (condition) { |
If else then with *ngIf
1 | <div class="case-3"> |
If else then with @if
With @if directive, you can use the following syntax, it’s more simple and readable:
1 | <div class="case-3"> |
Conclusion
既然Angular已经有ngIf, ngFor, ngSwitch等内置的结构性指令,为什么还要引入新的@if,@for, @switch呢?主要有以下原因
- 更简洁的语法,比如要实现if - else if - … - else的逻辑,使用
ngIf就会显得很臃肿。而使用@if就可以很好的解决这个问题。 - 更好的类型检查机制,这个不知道是怎么实现的。
- 更好的运行时性能,Angular编译器会将
@if,@for,@switch编译成更高效的代码,这样可以减少运行时的开销。 - 更小的包体积,最多可以减少30kb的包体积。
- 不需要额外导入
CommonModule模块,直接使用即可,ngIf等指令则需要导入CommonModule模块。