[英]Angular: Accessing a template reference variable located inside `async` pipe element
I want to access a template reference variable using @ViewChild
while the element is inside an element with async
pipe present as follows:我想在元素位于
async
pipe 的元素内时使用@ViewChild
访问模板引用变量,如下所示:
<ng-container *ngIf="productTemplates$ | async as templates; else loading">
<div class="row">
<mat-checkbox #selectAll (change)="toggleAllTemplates($event)">Select All</mat-checkbox>
</div>
</ng-container>
How can I safely access the #selectAll
reference early in the lifecycle of the component (like in ngAfterViewInit
) while it is not present until the API call for products is returned?如何在组件的生命周期早期安全地访问
#selectAll
引用(如在ngAfterViewInit
中),而它在返回 API 产品调用之前不存在?
I would replace the @ViewChild
with @ViewChildren
instead.我会用
@ViewChildren
替换@ViewChild
。 It might seem not that intuitive at first, but the reasoning behind it is that @ViewChildren
always returns you a QueryList
that is not null
inside the ngAfterViewInit
lifecycle method.一开始可能看起来不那么直观,但其背后的原因是
@ViewChildren
总是在ngAfterViewInit
生命周期方法中返回一个不是QueryList
的null
。
You can then subscribe to the changes
observable to be notified each time this query list changes然后,您可以订阅可观察到的
changes
,以便在每次此查询列表更改时得到通知
@ViewChildren('selectAll', { read: MatCheckbox }) selectAllCheckboxes!: QueryList<MatCheckbox>;
ngAfterViewInit() {
this.selectAllCheckboxes.changes.pipe(
filter(() => this.selectAllCheckboxes.length > 0)
).subscribe(() => this.doSomethingWithTheCheckbox());
}
private doSomethingWithTheCheckbox() {
const selectAllCheckbox = this.selectAllCheckboxes.first;
// here you should be able to safely use your selectAllCheckbox
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.