简体   繁体   中英

Angular jquery data table issue / ngFor

I have one issue related to query data tables with ngFor directive, if I use jquery data tables with static data, it works fine, but while using data table with *ngFor directive getting data from http / api service, once I render the page in the first time, I see a perfect result, if I routes to another page and come back I see no data found message and All Table Data at the same time and data table functions like Paging, Filter, search are not working, I should refresh the page again to fix this !!

please assist how to resolve that issue ?!!

 import { Component, OnInit } from '@angular/core'; import { TestserviceService } from '../services/testservice.service'; declare var $: any; declare var jQuery: any; @Component({ selector: 'Test', templateUrl: './test.html' }) export class Test implements OnInit { posts: any[]; constructor(public mytestservice: TestserviceService) { this.mytestservice.getposts().subscribe(response =>{ this.posts = response.json(); }); } ngOnInit() { $(function(){ $('#posts').DataTable({ responsive: true }); }); } } 
 <div class="card-body"> <table class="table table-hover" id="posts" width="100%"> <thead> <tr> <th>SEQ </th> <th>User ID</th> <th>ID</th> <th>Title</th> <th>Body</th> </tr> </thead> <tbody> <tr *ngFor="let post of posts"> <td>###</td> <td>{{post.userId}}</td> <td>{{post.id}}</td> <td>{{post.title}}</td> <td>{{post.body}}</td> </tr> </tbody> </table> </div> 

Try this piece of code -

constructor(public mytestservice: TestserviceService) { 

    this.mytestservice.getposts().subscribe(response =>{
      this.posts = response.json();
      $('#posts').DataTable({
        responsive: true
      });
    });

  }

  ngOnInit() { }

this is the solution

  ngOnInit() { this.mytestservice.getposts().subscribe(response =>{ this.posts = response.json(); $(function(){ $('#posts').DataTable({ responsive: true }); }); }); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM