首页 > 解决方案 > 角度变化。订阅不触发

问题描述

我想在组件完全渲染后更新它的 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');
    });
}

标签: angularangular2-observables

解决方案


它对我来说很好,只是做了一些小的改动。这就是我最终的结果:

模板

<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();

推荐阅读