Maris
Maris

Reputation: 4776

How to wait until ng2 will complete changing the DOM

I have a print functionality in my web-app. I am using jquery print plugin to display in print-preview only few elements in dom. I want to make sure that I start printing only when all data have been rendered. In current implementation - sometimes print preview appears with not all information in dom(I think ng2 uses some kind of deferred operations).

Take a look at the sample:

@Component(...)
export class MyCoolComponent{|

myModel:MyModel;


print(){
   _myService.fetchDataSomehow().subscribe((newData:MyModel)=>{
       this.myModel = newData;
       // I need to wait until ng2 will adjust dom with new data in synchronous manner
       $(this._el).print();
   })
}
}

Template:

<div>
  {{myModel.field1}}
  {{myModel.field2}}
  {{myModel.field3}}
  //...and a lot of other fields from myModel
</div>

I know that I can use setTimeout(()=>{...}, 1), but it looks silly. Is there more solid approach to wait until angular 2 adjusted dom due to model changes?

Upvotes: 4

Views: 2118

Answers (2)

mrcolombo
mrcolombo

Reputation: 587

A different approach would be just to add *ngIf to your html.

If you want to render nothing until there is a value in myModel, do something like.

<div *ngIf="myModel">
  {{myModel.field1}}
  {{myModel.field2}}
  {{myModel.field3}}
</div>

This will check to see if there is any value to myModel. If it does, then it will render.

You can also add "loading text" as you are fetching by checking if myModel has no value and handling it appropriately

<div *ngIf="!myModel">
     Fetching Data...
</div>

Upvotes: 0

kit
kit

Reputation: 4920

checkout ngAfterViewChecked in the docs, maybe it's what you are looking for.

Upvotes: 2

Related Questions