我已经开始在角度5中创建一个简单的SPA,但是现在我陷入了每次将鼠标悬停在卡片上时都会调用getFullPathUrl()函数的问题。函数getFullPathUrl()获得类似“ test.jpg”和尺寸的内容,并返回www.test.com/156x0/test/test.jpg。假设仅在初始化时设置img src吗?如果我错了,请更正我。现在,如果我将鼠标悬停在任何卡片功能上,都会被调用40次,而当鼠标从卡片上离开时,它将被再次调用多次。

  <div class="card" *ngFor="let item of galleries;let i = index;" [routerLink]="['/'+item.path]"
         (mouseenter)=" setBackground(item.image.fullpath)"
         (mouseover)="showCount = true" (mouseleave)="showCount = false">
        <img class="card-img-top"
             [src]="getFullPathUrl(item?.image?.fullpath,156)" alt="Card image cap">
        <div class="card-block">
            <h4 class="card-title imagesCount"></h4>
            <h4 class="card-title title">{{item.name}}</h4>
        </div>
    </div>

最佳答案

问题是您在模板上有一个函数调用。这意味着在每次更改检测时将调用该函数。由于鼠标事件会触发更改检测,因此您有这种行为。您需要做的是在组件的属性上设置该函数的返回值,然后在模板上添加一个变量。

编辑

考虑到您的情况,您可能会遇到类似

[src]="rootPath + ‘156x0/test’ + item?.image”


其中rootPath是组件上的变量。就像是

rootPath: string = “www.test.com/“


就解决方案而言,这显然不是最漂亮的方法,但是我只是在解释您将现有功能调用分解为变量所要做的事情。而且您的路径组成似乎有些棘手,因此这就是为什么您需要那种奇数串连接的原因。

09-30 13:32
查看更多