等待 DOM 就绪状态在动态添加的元素上初始化 amchart



我正在使用动态网格,它允许用户创建各种类型的小部件。

这些小部件是在 ngFor 指令中创建的,所以我只是将一个新小部件推送到数组并想要初始化图表,但似乎该元素已经不在 DOM 中。

我知道可能有对 ViewChild 的引用,但没有任何支持的最大长度。另外,我可以轻松使用 setTimeout,但这对我来说似乎不是一个很好的方法。此外,amchart 有一个 ready(( 函数,但在这种情况下,它没有帮助,因为它指的是库 init 而不是图表容器。

// Main array of data
let widgets = [
{type: 'chart', id:'uniqueID'};
];
// Simply generate a new widget
createChart() {
let chartWidget = {type: 'chart', id: 'uniqueID2'};
this.widgets.push(chartWidget);
let amchart = this._amChartsService
.makeChart(chartWidget.id, {chartOpt});
};
<div *ngFor="let widget of widgets>
<div [attr.id]="widget.id"></div>
</div>

此解决方案仅适用于新创建的 HTML 元素。保存数据并再次加载后,有一个生命周期事件为我处理它。

是否有像 ngDoCheck 这样的功能可以让我知道 ngFor 指令是否实际创建了元素并且它可用?

或者任何安查特主解决方案?

这很容易,但我必须改变主意。

正如我建议的那样,Angular 具有各种生命周期事件,所以我设法创建了一个新组件并使用预定义的 AfterViewInit,如下所示。

<!-- Parent template with gridster -->
<div *ngFor="let widget of widgets>
<chart [widget]="widget"></chart>
</div>
// "chart" component
export class Chart implements AfterViewInit {
@Input() widget:Chart;
/**
* After view is inited
* Now I know that HTML element is in DOM
*/
ngAfterViewInit() {
this.createChart();
}
}

我没有包括代码的所有部分,但任何会在这个问题上挣扎的人都应该知道如何继续。

最新更新