我应该如何配置Angular 8的新子视图?
@ViewChild('searchText', {read: ElementRef, static: false})
public searchTextInput: ElementRef;
vs
@ViewChild('searchText', {read: ElementRef, static: true})
public searchTextInput: ElementRef;
哪个更好?什么时候我应该使用static:true vs static:false?
这里是因为升级到Angular 8后,ngOnInit中的ViewChild为空。
静态查询在ngOnInit之前填充,而动态查询(Static: false)在ngOnInit之后填充。换句话说,如果在你设置static: false后,ngOnInit中的viewchild现在是null,你应该考虑将其更改为static: true或将代码移动到ngAfterViewInit。
看到https://github.com/angular/angular/blob/master/packages/core/src/view/view.ts L332-L336
The other answers are correct and explain why this is the case: Queries dependant on structural directives, e.g. a ViewChild reference inside an ngIf, should run after the conditional of this directive has been resolved, ie after change detection. However, one may safely use static: true and thus resolve the queries before ngOnInit for unnested references. Imho this particular case bears mentioning as a null exception could likely be the first way you'll encounter this particularity, as it was for me.