I have this component:
<div #widget
class="widget">
</div>
@ViewChild('widget') widget!: any;
ngOnInit() {
console.log(this.widget.nativeElement) //returns undedined
}
However it is working if I use native api:
console.log(document.querySelector('.widget'));
Then I've done some research and figure out that:
@ViewChild('widget', {static: true}) widget!: any;
It is fixed the native element looking to the answers to this question, however the main answers there is quite confusing:
In most cases you will want to use {static: false}. Setting it like this will ensure query matches that are dependent on binding resolution (like structural directives *ngIf, etc...) will be found.
and
The { static: true } option was introduced to support creating embedded views on the fly. When you are creating a view dynamically and want to acces the TemplateRef, you won't be able to do so in ngAfterViewInit as it will cause a ExpressionHasChangedAfterChecked error. Setting the static flag to true will create your view in ngOnInit.
So now I do have a few questions
- Does it mean that
@ViewChild('widget', {static: true}) widget!
is equal todocument.querySelector('.widget')
? - Is they are not equal in what cases I have to use
@ViewChild('widget', {static: true}) widget!
vsdocument.querySelector('.widget')
? - In what cases i should use
@ViewChild('widget', {static: true}) widget!
vs@ViewChild('widget', {static: false}) widget!
? - In my case I am not using any dynamic views but the refered answer suggesting to use
{static: false}
is quite bizarre.