首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角changes.subscribe不点火

角changes.subscribe不点火
EN

Stack Overflow用户
提问于 2018-07-26 17:53:50
回答 1查看 2.9K关注 0票数 2

我想在组件完全呈现后更新它的UI。因为它呈现的是for中的元素,所以我的理解是,在与UI交互之前,我需要使用订阅来检查要首先创建的元素。

根据我读过的例子,这就是我想出来的。但是,没有发生任何事情,因为我订阅中的console.log语句永远不会触发。没有错误。就好像我的订阅没有看到任何变化。我的逻辑中有什么明显的遗漏吗?

模板标记:

代码语言:javascript
复制
<ng-container *ngFor="let item of items; let i = index;">
    <input *ngIf="..." #inputItem>

角(5):

代码语言:javascript
复制
@ViewChildren('inputItem', {read: ViewContainerRef }) inputItems: QueryList<ViewContainerRef>;

ngAfterViewInit(): any {
    this.inputItems.changes.subscribe(() => {
        console.log('items created');
    });
}
EN

回答 1

Stack Overflow用户

发布于 2018-07-26 18:17:32

对我来说,只要做几处小小的改动就行了。这就是我最后的结局:

模板

代码语言:javascript
复制
<tr *ngFor='let product of filteredProducts' >
  <input *ngIf='product.imageUrl' #inputItem type='text'>

组件

代码语言:javascript
复制
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),因此没有订阅(也没有未订阅)。

如果您想从上面取消订阅,那么首先需要将订阅放入一个类变量中:

代码语言:javascript
复制
this.sub = this.inputItems.changes.subscribe(...);

然后在毁灭中:

代码语言:javascript
复制
this.sub.unsubscribe();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51544875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档