我想在组件完全渲染后更新其 UI。因为它是在 for 中渲染元素,所以我的理解是我需要使用订阅来检查在与 UI 交互之前首先创建的元素。
根据我读过的示例,这就是我的想法。但是,我的订阅中的 console.log 语句从未触发,因此没有任何反应。没有错误。就好像我的订阅没有看到任何变化。我的逻辑中是否有明显缺失的东西?
模板标记:
<ng-container *ngFor="let item of items; let i = index;">
<input *ngIf="..." #inputItem>
Angular (5):
@ViewChildren('inputItem', {read: ViewContainerRef }) inputItems: QueryList<ViewContainerRef>;
ngAfterViewInit(): any {
this.inputItems.changes.subscribe(() => {
console.log('items created');
});
}
最佳答案
它对我来说效果很好,只是做了一些小的改变。这就是我最终得到的结果:
模板
<tr *ngFor='let product of filteredProducts' >
<input *ngIf='product.imageUrl' #inputItem type='text'>
组件
import { Component, OnInit, ViewChildren,
QueryList, AfterViewInit, ElementRef } from '@angular/core';
@ViewChildren('inputItem') inputItems: QueryList<ElementRef>
ngAfterViewInit(): void {
this.inputItems.changes.subscribe(value => {
console.log(value);
this.inputItems.map((item => item.nativeElement.style.backgroundColor = 'red') )
}
);
}
更新 2019 年 8 月 8 日回复:取消订阅:
从技术上讲,您不必取消订阅元素上定义的任何 Observables,因为它们会在表单被销毁时被销毁。
但是,开发人员总体上已经转向更明确的方法,并使用这样的规则:如果您订阅,则应始终取消订阅。
在我现在使用的应用程序中,我专门使用异步管道(如下所示: https://github.com/DeborahK/Angular-RxJS ),因此没有订阅(也没有取消订阅)。
如果您确实想取消订阅上述内容,您首先需要将订阅放入类变量中:
this.sub = this.inputItems.changes.subscribe(...);
然后在销毁中:
this.sub.unsubscribe();
关于 Angular 变化。订阅不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51544875/