问题描述: 在使用Ag-grid和Angular的组合时,发现首次数据渲染时并不会触发Ag-grid的事件。
解决方法:
以下是两种解决方法的代码示例:
方法一:手动触发数据渲染事件 在Ag-grid组件的ngAfterViewInit生命周期钩子中手动调用api.sizeColumnsToFit()方法触发数据渲染事件。
import { Component, OnInit, ViewChild } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
@Component({
selector: 'app-ag-grid',
templateUrl: './ag-grid.component.html',
styleUrls: ['./ag-grid.component.scss']
})
export class AgGridComponent implements OnInit {
@ViewChild('agGrid') agGrid: AgGridAngular;
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.agGrid.api.sizeColumnsToFit();
}
}
方法二:使用setTimeout延迟触发数据渲染事件 在Ag-grid组件的ngAfterViewInit生命周期钩子中使用setTimeout延迟一段时间后再触发数据渲染事件。
import { Component, OnInit, ViewChild } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
@Component({
selector: 'app-ag-grid',
templateUrl: './ag-grid.component.html',
styleUrls: ['./ag-grid.component.scss']
})
export class AgGridComponent implements OnInit {
@ViewChild('agGrid') agGrid: AgGridAngular;
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit(): void {
setTimeout(() => {
this.agGrid.api.sizeColumnsToFit();
}, 100);
}
}
以上两种方法都可以解决Ag-grid的Angular首次数据渲染不会触发的问题。可以根据具体情况选择适合的解决方法。