Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a function in jQuery once HTML is completely rendered dynamically in Angular 4?

I am using Angular 4 for my web template. HTML is generated once the HTTP get method is called inside the constructor, the response of which creates the HTML.

The above works fine.

I am also using jQuery with Angular and trying to initialize a function on this page.

$(function() {
    Books.init();
});

I have tried calling the above code inside various lifecycle hooks. For example, ngOnInit(), ngOnChanges(), ngDoCheck, ngAfterViewInit(), ngAfterContentInit() but still the code gets called before the view is completely rendered by the API response.

Is there any way to get an event which assures that the view is completely rendered and then I can load my jQuery?

Please note: I have called this function inside a setTimeOut call with a small time delay and this works in that.

like image 334
Anmol G Avatar asked Jan 02 '18 10:01

Anmol G


1 Answers

I faced the same problem. I did not got any solution so I played with variables.

First of all take the length of how many elements you are going to render.

bookCount: number = 0;

Then in ngAfterContentChecked()

ngAfterContentChecked() {
if(this.bookCount > 0 && this.bookCount == document.getElementsByClassName('bk-book').length)
{
  this.getInitdata();
}

This worked for me temporarily, still looking for better solution.

like image 105
Jay Momaya Avatar answered Nov 04 '22 14:11

Jay Momaya