I need to apply jquery plugin to radio buttons in Angular2 using Typescript.

If I assign in ngAfterViewChecked, it is called many times and the control is refreshed multiple times.

What is the alternate solution for calling the javascript method after DOM is ready?

4

There are 4 answers

4
SeleM On

Try ngAfterViewInit and have a look here.

0
stolorma On

I don't exactly know what you need to do and or achieve but I will show you my solution for a similar use case.

My Problem was that I needed to scroll down a div on load. AfterViewChecked got executed multiple times but I needed to scroll down in this lifecycle. Thats what I did, maybe it helps you:

    public scrollSuccessfull = false; // global variable


    public ngAfterViewChecked(): void {
        if (!this.scrollSuccessful) {
          // gets executed as long as the scroll wasnt successfull, so the (successful) scroll only gets executed once
          this.scrollSuccessful = this.scrollToBottom(this.internal ? this.internalChatDiv : this.externalChatDiv);
        }
      }

    private scrollToBottom(element: ElementRef): boolean {
        if (element) {
          element.nativeElement.scrollTop = element.nativeElement.scrollHeight;
          return element.nativeElement.scrollTop !== 0;
        }

        return false;
      }
0
Amr Abdalrahman Ahmed On

I have been using ngAfterViewChecked when I depend on the DOM being ready.

import { Component, AfterViewChecked } from '@angular/core'; 

export class NavBar implements AfterViewChecked{

   ngAfterViewChecked(){
      // jquery code here
   }
}
0
Richard On

ngAfterViewChecked() would be invoked once the DOM tree get any change.

So if the DOM tree got change for many times, the ngAfterViewChecked() method would be invoked many times.

Suggest not to put business logic in this method. But only the screen refresh related logic instead, like to scroll the window to bottom if new message is coming in.