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.
@Component({
selector: 'app-root',
template: `
<button type="button" (click)="toggleExists()">Toggle Component</button>
<hr>
<app-if-example *ngIf="exists">
Hello
</app-if-example>
`
})
export class AppComponent {
exists = true;
toggleExists() {
this.exists = !this.exists;
}
}
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