【问题标题】:Angular jquery data table issue / ngForAngular jquery 数据表问题 / ngFor
【发布时间】:2018-05-02 18:18:31
【问题描述】:

我有一个与使用 ngFor 指令查询数据表相关的问题, 如果我使用带有静态数据的 jquery 数据表,它工作正常,但是在使用带有 *ngFor 指令的数据表从 http / api 服务获取数据时,一旦我第一次渲染页面,我会看到一个完美的结果,如果我路由转到另一个页面并返回我同时看到未找到数据消息和所有表数据,并且分页、过滤、搜索等数据表功能不起作用,我应该再次刷新页面以解决此问题!

请帮忙解决这个问题?!!

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>

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    试试这段代码-

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

    【讨论】:

      【解决方案2】:

      这就是解决办法

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

      【讨论】:

      • 不用$(function(){
      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2018-03-12
      • 2016-11-28
      • 2012-01-14
      • 1970-01-01
      相关资源
      最近更新 更多