繁体   English   中英

角度变化。订阅不触发

[英]angular changes.subscribe not firing

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

UPDATE 8/8/19 RE:取消订阅:

从技术上讲,您不必取消订阅在元素上定义的任何可观察对象,因为在销毁表单时它们将被销毁。

但是,一般而言,开发人员已转向一种更为明确的方法,并一直在使用以下规则:如果您订阅,则应始终退订。

在我现在使用的应用程序中,我仅使用异步管道(如此处所示: https : //github.com/DeborahK/Angular-RxJS ),因此没有订阅(也没有取消订阅)。

如果确实要取消上述订阅,则首先需要将订阅放入类变量中:

this.sub = this.inputItems.changes.subscribe(...);

然后在销毁:

this.sub.unsubscribe();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM