Sometimes, we want to use @ViewChild in *ngIf with Angular.
In this article, we’ll look at how to use @ViewChild in *ngIf with Angular.
How to use @ViewChild in *ngIf with Angular?
To use @ViewChild in *ngIf with Angular, we set the static
option to false
and use a setter.
For instance, we write
<div id="layout" *ngIf="display">
<div #contentPlaceholder></div>
</div>
to add a div with ref contentPlaceholder
in the div that’s displayed when display
is true
.
Then in our component code, we write
export class AppComponent {
display = false;
private contentPlaceholder: ElementRef;
@ViewChild("contentPlaceholder") set content(content: ElementRef) {
if (content) {
this.contentPlaceholder = content;
}
}
}
to add the setter by add a function after set
.
Then when content
, which is the element with the ref is defined, we set this.contentPlaceholder
to content
.
In Angular 8 or later, we add the static
option by writing
export class AppComponent {
display = false;
private contentPlaceholder: ElementRef;
@ViewChild("contentPlaceholder", { static: false }) set content(
content: ElementRef
) {
if (content) {
// initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
}
to set static
to false
to watch for changes with the setter.
Conclusion
To use @ViewChild in *ngIf with Angular, we set the static
option to false
and use a setter.