NgIf Directive

The ngIf directive conditionally adds or removes content from the DOM based on whether or not an expression is true or false.

Here's our app component, where we bind the ngIf directive to an example component.

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <button type="button" (click)="toggleExists()">Toggle Component</button>
  5. <hr>
  6. <app-if-example *ngIf="exists">
  7. Hello
  8. </app-if-example>
  9. `
  10. })
  11. export class AppComponent {
  12. exists = true;
  13. toggleExists() {
  14. this.exists = !this.exists;
  15. }
  16. }

View Example

Clicking the button will toggle whether or not IfExampleComponent is a part of the DOM and not just whether it is visible or not. This means that every time the button is clicked, IfExampleComponent will be created or destroyed. This can be an issue with components that have expensive create/destroy actions. For example, a component could have a large child subtree or make several HTTP calls when constructed. In these cases it may be better to avoid using ngIf if possible.

原文: https://angular-2-training-book.rangle.io/handout/directives/ng_if_directive.html