How should I configure the new Angular 8 view child?
@ViewChild('searchText', {read: ElementRef, static: false})
public searchTextInput: ElementRef;
vs
@ViewChild('searchText', {read: ElementRef, static: true})
public searchTextInput: ElementRef;
Which is better? When should I use static:true
vs static:false
?
Best Answer
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.Example of when to use
static: false
:The
static: false
is going to be the default fallback behaviour in Angular 9. Read more here and hereThe
{ static: true }
option was introduced to support creating embedded views on the fly. When you are creating a view dynamically and want to acces theTemplateRef
, you won't be able to do so inngAfterViewInit
as it will cause aExpressionHasChangedAfterChecked
error. Setting the static flag to true will create your view in ngOnInit.Nevertheless:
Be aware though that the
{ static: false }
option will be made default in Angular 9. Which means that setting the static flag is no longer necessary, unless you want to use thestatic: true
option.You can use the angular cli
ng update
command to automatically upgrade your current code base.For a migration guide and even more information about this, you can check here and here
A nice use-case for using
static: true
, is if you are usingfromEvent
to bind to an element defined in the template. Consider the following template:You can then handle events on this element without the need of using subscriptions or init hooks (if you don't want to or cannot use angular event binding):
It is important to use
defer
. This will make sure the observable is only resolved when it's subscribed to. This will happen before thengAfterViewInit
gets triggered, when theasync
pipe subscribes to it. Because we are usingstatic: true
, thethis.thumb
is already populated.