简体   繁体   English

Angular2:函数在渲染时调用了两次

[英]Angular2: function called twice at rendering

I have a function that is called for each iteration. 我有一个为每次迭代调用的函数。

And not excpectedly, this function is called twice at each iteration. 并不出乎意料的是,此函数在每次迭代中都会被调用两次。

public setLevel(deviceId: string, averageFps: number): void {
    let device = `device-${deviceId}`;

    // (<HTMLElement>document.querySelector(`#${device} .level-fps-wrapper .level-fps`)).style.width = `${averageFps / 300 * 100}%`;
    console.log(device);
}

Here is the html template 这是HTML模板

<div class="container">
<div class="row">
    <h1 class="header">Devices</h1>
    <div class="col l4 m6 s12 clickable" *ngFor="let device of this.devices" (click)="goToDevice(device)">
        <div class="card" [id]="'device-' + device.device._id">
            <div class="card-content">
                <div class="row no-margin-bottom">
                    <div class="col s2">
                        <img class="circle circle-element" [src]="'./app/devices/images/' + device.device.os + '_logo.png'" alt="">
                    </div>
                    <div class="col s10">
                        <span class="card-title">{{ device.device.name }}</span>
                        <p>
                            {{ device.averageFps | number: '.1-2' }} fps
                        </p>
                    </div>
                </div>
            </div>
            <div class="card-action level-fps-wrapper">
                <div class="level-fps">{{ this.setLevel(device.device._id, device.averageFps) }}</div>
            </div>
        </div>
    </div>
</div>

This is the output 这是输出

这是输出

It should be 3 lines instead of 6. 应该是3行而不是6行。

Someone could explain it to me? 有人可以向我解释吗? Is there something to do with angular Lifecycle hooks? 与角度生命周期挂钩有关吗?

Thanks for your answers! 感谢您的回答!

Yes, this is quite usual. 是的,这很平常。 Similar to angular 1 there is no way that angular can tell whether the result of the function will have changed, so it calls it on every digest loop. 与角度1相似,角度也无法告诉函数结果是否会更改,因此它在每个摘要循环上都调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM