[英]How to execute a function, when angular ngFor creates an element in the DOM?
我有一個服務器端腳本,它將傳感器信息保存到數據庫中。 然后,此信息應顯示在前端。 前端是一個 angular 應用程序。 數據庫中的傳感器信息將顯示在基於冰沙 package 的圖表中。 在頁面加載期間的前端,我在ngOnInit
function 中調用 API 端點,並返回 output,如下所示:
[
{
"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 中的冰沙顯示一些必要的畫布:
<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 后對每個元素調用 function,這將初始化冰沙圖以傳輸數據。 我不能使用ngAfterViewinit
function,因為 API 調用是異步的,它在請求返回數據之前執行。 我在一些類似的帖子中讀到它,我可以創建一個指令來執行此操作,但很可能是由於缺乏 angular 的知識,我無法理解並復制它(意思是:我得到了它背后的想法也復制了所有代碼,但沒有一個工作)
有人可以告訴我如何解決這個問題並解釋其背后的邏輯,以便像我這樣對 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 更改為 function 您要調用的名稱,並且不要忘記在模塊的聲明數組中導入此指令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.