我想在组件完全呈现后更新它的UI。因为它呈现的是for中的元素,所以我的理解是,在与UI交互之前,我需要使用订阅来检查要首先创建的元素。
根据我读过的例子,这就是我想出来的。但是,没有发生任何事情,因为我订阅中的console.log语句永远不会触发。没有错误。就好像我的订阅没有看到任何变化。我的逻辑中有什么明显的遗漏吗?
模板标记:
<ng-container *ngFor="let item of items; let i = index;">
<input *ngIf="..." #inputItem>角(5):
@ViewChildren('inputItem', {read: ViewContainerRef }) inputItems: QueryList<ViewContainerRef>;
ngAfterViewInit(): any {
this.inputItems.changes.subscribe(() => {
console.log('items created');
});
}发布于 2018-07-26 18:17:32
对我来说,只要做几处小小的改动就行了。这就是我最后的结局:
模板
<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') )
}
);
}更新8/8/19 RE:取消订阅:
从技术上讲,您不应该从定义在元素上的任何可观测值中取消订阅,因为当表单被销毁时,它们将被销毁。
然而,一般来说,开发人员已经转向了一种更加明确的方法,并且一直在使用这样的规则:如果您订阅,您应该始终取消订阅。
在我现在使用的应用程序中,我只使用异步管道(如这里所示:https://github.com/DeborahK/Angular-RxJS),因此没有订阅(也没有未订阅)。
如果您想从上面取消订阅,那么首先需要将订阅放入一个类变量中:
this.sub = this.inputItems.changes.subscribe(...);然后在毁灭中:
this.sub.unsubscribe();https://stackoverflow.com/questions/51544875
复制相似问题