[英]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.