【问题标题】:Wait for DOM-ready state to init amchart on dynamically added element等待 DOM 就绪状态在动态添加的元素上初始化 amchart
【发布时间】:2019-09-09 20:01:26
【问题描述】:

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

这些小部件是在 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 指令是否实际创建了元素并且它是否可用?

或任何 amcharts 主解决方案?

【问题讨论】:

    标签: angular dynamic amcharts


    【解决方案1】:

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

    正如我所建议的,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();
        }
    }
    

    我没有包括所有部分的代码,但任何想解决这个问题的人都应该知道如何继续。

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 1970-01-01
      • 2014-06-24
      • 2021-07-10
      • 2023-04-01
      • 2014-03-29
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      相关资源
      最近更新 更多