angular - 角度变化。订阅不触发
问题描述
我想在组件完全渲染后更新它的 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');
});
}
解决方案
它对我来说很好,只是做了一些小的改动。这就是我最终的结果:
模板
<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 回复:退订:
从技术上讲,您不必取消订阅元素上定义的任何 Observable,因为它们将在表单被销毁时被销毁。
然而,一般来说,开发人员一直在转向一种更明确的方法,并一直在使用这样的规则:如果您订阅,您应该始终取消订阅。
在我现在使用的应用程序中,我只使用异步管道(如下所示:https ://github.com/DeborahK/Angular-RxJS ),因此没有订阅(也没有取消订阅)。
如果您确实想从上面取消订阅,您首先需要将订阅放入一个类变量中:
this.sub = this.inputItems.changes.subscribe(...);
然后在销毁:
this.sub.unsubscribe();
推荐阅读
- python - 使用 tz 将 UNIX 时间转换为本地时间时间戳
- java - JavaFX:当用户单击 X 按钮时显示对话框窗口?
- html - 在 Go 中匹配 html 标记之外的 html 文本的最佳方法是什么?
- reactjs - 我应该向客户端 React 应用程序公开 Web API 吗?
- java - 带有 java-platform 插件的父 gradle 模块
- amazon-dynamodb - 我应该在这个 dynamodb 表中选择哪一列作为二级索引?
- javascript - 为什么我不能对这个元素应用任何东西?
- asp.net - ASP.NET - 实体框架下拉列表
- jquery - jQuery动画队列:true同时发生
- arrays - 将数组分成两部分,使它们的总和之差最小