Method call after view (DOM) is updated (in Angular 2)

Suppose 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 use it somewhere in my template: ...<select my-select [(ngModel)]="someReference">...

At some point, I change the value of someReference in the component: someReference = "newValue"

What's happening now: The doSomeStuffAfterViewIsUpdated function is called before the DOM is updated. This means the console is showing the old selection value.

What I want: The doSomeStuffAfterViewIsUpdated function should be called after the DOM is updated with angular, so the console shows "newValue".

What should I use instead of ngOnChanges in order for it to work as I want?

Note that it is important here that the code is executed after the DOM is updated. The question is not how can I access the new value of the element.

thank!

+3


source to share


1 answer


I am a little late to the party, but since I had a similar problem and a likely solution, I thought I would share:

What you are looking for is MutationObservers ( CanIUse ); I solved a very similar problem with a directive like this (simplified for ... simplicity ?: 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 attribute, and children, etc. will be changed in the DOM (or added, removed, etc.)

You may not need it ngOnChanges

at all depending on your use case, and this will make the code a little cleaner.

+1


source







All Articles