当 angular ngFor 在 DOM 中创建一个元素时,如何执行一个函数?

How to execute a function, when angular ngFor creates an element in the DOM?

我有一个服务器端脚本,可以将传感器信息保存到数据库中。然后,此信息应显示在前端。前端是一个 angular 应用程序。来自数据库的传感器信息将显示在基于冰沙包装的图表中。在页面加载期间的前端,我在 ngOnInit 函数中调用了一个 API 端点,并且 returns 的输出如下:

[
    {
        "id": 1,
        "name": "CPU Usage",
        "frequency": 5,
        "unit": "%"
    },
    {
        "id": 2,
        "name": "Memory Usage",
        "frequency": 4,
        "unit": "GB"
    }
]

然后我将其加载到数组中:

  public charts: Chart[] = [];

  constructor(private httpClient: HttpClient, private dataService: ApiService) { }

  ngOnInit(): void {
    this.httpClient.get<any>(this.dataService.baseUrl + '/measurable/active').subscribe({
      next: data => {
        for (let i = 0; i < data.length; i++) {
          let smoothie = new SmoothieChart();

          this.charts.push(new Chart(data[i].id, data[i].name, data[i].unit, smoothie));
        }

        console.debug(this.charts);
      },
      error: error => {
        console.error('Could not load any measurable', error.message);
      }
    })
  }

并在 ngFor:

的帮助下,在 html 中为冰沙显示一些必要的 canvas'
<div class="container">
  <div class="row">
    <div class="col-md-6 mx-auto">
      <p>dashboard works!</p>
      <div class="row" *ngFor="let chart of charts">
        <label>{{ chart.name }}({{ chart.unit }})</label>
        <canvas id="{{ chart.id }}" style="width:100%; height:200px" width="1262" height="200"></canvas>
      </div>
    </div>
  </div>
</div>

在此加载过程中,我想在显示 canvas 后对每个元素调用一个函数,这将初始化 smoothie 图以流式传输数据。 我不能使用 ngAfterViewinit 函数,因为 API 调用是异步的,它在请求 returns 数据之前执行。 我在 similar 中读到我可以创建一个指令来执行此操作,但是很可能是由于 angular 中缺乏知识我无法理解并重现它(意思是:我明白了它后面也复制了所有代码,但是 none 有效)

谁能告诉我如何解决这个问题并解释其背后的逻辑,以便像我这样 angular 没有经验的人也能理解它?

在 angular 中创建一个指令,例如:-

@Directive({
  selector: '[refresh]'
})
export class RefreshDirective implements OnInit {
  @Output() init = new EventEmitter();
  ngOnInit() {
     this.init.emit()
  }
}

并将您的 html 更改为:-

<div class="container">
  <div class="row">
    <div class="col-md-6 mx-auto">
      <p>dashboard works!</p>
      <div class="row" *ngFor="let chart of charts">
        <label>{{ chart.name }}({{ chart.unit }})</label>
        <canvas id="{{ chart.id }}" style="width:100%; height:200px" width="1262" height="200" refresh (init) = "myMethod()"></canvas>
      </div>
    </div>
  </div>
</div>

将 myMethod 更改为您要调用的函数名称,并且不要忘记在模块的声明数组中导入此指令。