3

i try to use jQuery Bootgrid together with Angular 2. The Problem is that that Bootgrid inspects an existing Table, but with angular2 my data is based on an asyncrone source.

I try to initialize the grid later when the data is set in the controller with no luck. I think that the grid have to be initialized AFTER the DOM was updated by angular2. Is there such a "after component-dom update"-Event? Or any other ideas?

Here my Code:

   records: Record[] = []
   grid: any

    ngOnInit() {
        this._recordService.getAllRecords().subscribe(
            data=> { this.records = data },
            error=> { alert(error) }
        )
            .add(() => setTimeout(() => this.initGrid(), 50));
    }


    initGrid() {
        this.grid = jQuery("#grid-basic");
        var ref = this;
        this.grid.bootgrid({
          ...config Stuff...

        })
    }

That will work only because of the ugly "setTimeout". Without the timeout the table will display "no data" (my bootgrid info label of the record count is updated with correctly)

Thanks for any ideas!

Hemant Desusa
  • 181
  • 2
  • 6

2 Answers2

3

There is the AfterViewChecked event, which is triggered every time the DOM is updated. This can be received by implementing the AfterViewChecked Typescript interface, which simply means you will have to add the method ngAfterViewChecked().

ngOnInit() {
    this._recordService.getAllRecords().subscribe(
        data=> { this.records = data },
        error=> { alert(error) }
    )
}

ngAfterViewChecked() {
  if (this.records.length > 0 && !this.isGridInitialized) this.initGrid();
}

initGrid() {
    this.isGridInitialized = true;
    this.grid = jQuery("#grid-basic");

    var ref = this;
    this.grid.bootgrid({
      ...config Stuff...

    })
}

Here is a working demo of AfterViewChecked: http://plnkr.co/edit/Edkba0Stgn95Whwz4vqq?p=preview . This demo shows that the ngAfterViewChecked method is called after the Observable completes (delayed with 5s).

AfterViewChecked is one of the Angular2 lifecycle hooks.

Lodewijk Bogaards
  • 19,777
  • 3
  • 28
  • 52
0

Couldn't you just wrap the promise around your initGrid function call

gridData.service.getData().then((data) => {
   initGrid(data);
});
inoabrian
  • 3,762
  • 1
  • 19
  • 27
  • That won't work. Keep in mind that the Data for the Table is loaded asyncron. When the Event is fired the table is empty > then bootgrid will init the empty table > then the data from the service is ready...too late for bootgrid – Hemant Desusa Jan 20 '16 at 16:17