【问题标题】:Angular2 execute Method after Rendering (Bootgrid)Angular2在渲染后执行方法(Bootgrid)
【发布时间】:2016-04-26 12:40:10
【问题描述】:

我尝试将 jQuery Bootgrid 与 Angular 2 一起使用。 问题是 Bootgrid 检查现有表,但使用 angular2 我的数据基于异步源。

我稍后在控制器中设置数据但没有运气时尝试初始化网格。我认为必须在 Angular2 更新 DOM 之后初始化网格。有没有这样的“组件-dom更新后”事件?还是有其他想法?

这是我的代码:

   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...

        })
    }

这只会因为丑陋的“setTimeout”而起作用。如果没有超时,表格将显示“无数据”(我的记录计数的 bootgrid 信息标签已正确更新)

感谢您的任何想法!

【问题讨论】:

    标签: angular jquery-bootgrid


    【解决方案1】:

    AfterViewChecked 事件,每次更新 DOM 时都会触发。这可以通过实现AfterViewChecked Typescript 接口来接收,这仅仅意味着您必须添加方法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...
    
        })
    }
    

    这是AfterViewChecked 的工作演示:http://plnkr.co/edit/Edkba0Stgn95Whwz4vqq?p=preview。这个demo展示了ngAfterViewChecked方法在Observable完成后调用(延迟5s)。

    AfterViewCheckedAngular2 lifecycle hooks 之一。

    【讨论】:

      【解决方案2】:

      难道你不能把承诺包装在你的 initGrid 函数调用中

      gridData.service.getData().then((data) => {
         initGrid(data);
      });
      

      【讨论】:

      • 那行不通。请记住,表的数据是异步加载的。当事件被触发时,表是空的 > 然后 bootgrid 将初始化空表 > 然后来自服务的数据准备好了......对于 bootgrid 来说太晚了
      猜你喜欢
      • 2019-04-27
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2012-01-25
      • 2017-01-05
      • 2017-08-21
      相关资源
      最近更新 更多