I came across the following issue which was fixed by the {static: false}
property in @ViewChild
.
This stackoverflow Q/A helped with that How should I use the new static option for @ViewChild in Angular 8?.
I wanted to understand this scenario better and how static
changes the outcome, as well as how change detection impacts this scenario. I've done some reading about change detection in the angular documentation and have found that extremely lacking.
I came up with a stackblitz that illustrates something that I don't understand. Stackblitz angular example
When clicking toggle
button twice, I get the following on the command line:
> undefined undefined
> undefined undefined
> undefined ElementRef {nativeElement: div}
> undefined ElementRef {nativeElement: div}
However I expect:
> undefined undefined
> undefined ElementRef {nativeElement: div}
> ElementRef {nativeElement: div} ElementRef {nativeElement: div}
> ElementRef {nativeElement: div} ElementRef {nativeElement: div}
Here is the logic for the code -- (see full code in stackblitz)
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
@ViewChild("contentPlaceholder", { static: true })
trueViewChild: ElementRef;
@ViewChild("contentPlaceholder", { static: false })
falseViewChild: ElementRef;
display = false;
constructor() {}
show() {
console.log(this.trueViewChild, this.falseViewChild);
this.display = true;
console.log(this.trueViewChild, this.falseViewChild);
}
}
My questions are:
- Why does the second row value of
this.falseViewChild
show as undefined. Shouldn't change detection have run after settingthis.display = false
and therefore it should not be undefined? - Why does
this.trueViewChild
stay undefined. I would expect it to find the element after the*ngIf
becomes true?