简体   繁体   English

更新视图(DOM)后的调用方法(在Angular 2中)

[英]Call method after view (DOM) is updated (in Angular 2)

Assume that I have the following directive: 假设我有以下指令:

import {Directive, Input, OnChanges } from '@angular/core'

@Directive({
  selector: 'select[my-select]'
})
export class NbSelect implements OnChanges {

  @Input() ngModel;

  constructor() {
  }

  ngOnChanges(changes) {
    doSomeStuffAfterViewIsUpdated();
  }

  doSomeStuffAfterViewIsUpdated() {
    console.log(jQuery('select[my-select]').val()); // this should write the new value
  }
}

I'm using it in somewhere in a template: ...<select my-select [(ngModel)]="someReference">... 我在模板中的某个地方使用它: ...<select my-select [(ngModel)]="someReference">...

At some point I change the value of someReference in a component: someReference = "newValue" 在某些时候,我更改了组件中someReference的值: someReference = "newValue"

What is happening now: The doSomeStuffAfterViewIsUpdated function is called before the DOM is updated. 现在发生了什么:在更新DOM之前调用doSomeStuffAfterViewIsUpdated函数。 Which means the console shows the old value of the select. 这意味着控制台显示选择的旧值。

What I want: The doSomeStuffAfterViewIsUpdated function should be called after the DOM is updated by angular, so the console shows the "newValue". 我想要的:在DOM更新DOM之后应该调用doSomeStuffAfterViewIsUpdated函数,因此控制台显示“newValue”。

What should I use instead of ngOnChanges to make it work like I want? 我应该使用什么而不是ngOnChanges来使它像我想要的那样工作?

Please note that the important thing here is that the code should run after the DOM update. 请注意,重要的是代码应该在DOM更新后运行。 The question is not about how can I access the new value of the element. 问题不在于如何访问元素的新值。

Thx! 谢谢!

I'm a bit late to the party, but since I had a similar problem and a probable solution, I thought I'd share: 我参加聚会有点晚了,但由于我有类似的问题和可能的解决方案,我想我会分享:

What you're looking for is MutationObservers ( CanIUse ); 您正在寻找的是MutationObserversCanIUse ); I solved a very similar issue with a directive similar to this (simplified for... simplicity? :P): 我用类似于此的指令解决了一个非常类似的问题(简化为......简单?:P):

ngOnChanges() {
    this.observer = new MutationObserver(() => { this.methodToCall() });
    this.observer.observe(this.elRef.nativeElement, this.observerOptions); // See linked MDN doc for options
}

private methodToCall(): void {
    this.observer.disconnect();
}

ngOnDestroy() {
    if(this.observer) { 
        this.observer.disconnect(); 
        this.observer = undefined;
    }
}

The MutationObserver callback will be triggered when either an attribute, children, etc is modified in the DOM (or added, deleted, etc) 当在DOM中修改属性,子等等(或添加,删除等)时,将触发MutationObserver回调

It is possible you won't need the ngOnChanges at all depending on your use case and it would make the code a bit cleaner too. 根据您的使用情况,您可能根本不需要ngOnChanges ,它也会使代码更清洁。

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

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