[英]ngFor creates unwanted copies of ng-template
我對 ngFor 指令有疑問,只是找不到解決方法:
<ng-container *ngIf="user.images.length > 0">
<div *ngFor="let image of images">
<img
*ngIf="image.isProfileImage; else noImage"
[src]="image.path"
/>
</div>
</ng-container>
<ng-template #noImage>
<img src="https://someplaceholder.com"/>
</ng-template>
因此,如果圖像是“個人資料圖像”,請使用它。 如果沒有,請使用帶有占位符圖像的模板。 在某些情況下,如果數組中有更多圖像並且它們都不是個人資料圖像,它會顯示ng-template
但重復多次(按數組中的圖像數)...,但它應該只顯示它一次並“跳出”循環。
我錯過了一些非常明顯的東西嗎?
沒有辦法跳出 ngFor 循環。 但是,有一種方法可以解決您的問題。
您可以在組件中創建一個方法,該方法將遍歷數組並檢查那里是否有配置文件圖像,然后您可以更改 HTML 並檢查數組是否包含配置文件圖像。 如果沒有,那么您可以只顯示 ngTemplate。
例子
<ng-container *ngIf="user.images.length">
<ng-container *ngIf="containsProfileImage(); else noImage">
<div *ngFor="let image of images">
<img
*ngIf="image.isProfileImage"
[src]="image.path"
/>
</div>
</ng-container>
</ng-container>
<ng-template #noImage>
<img src="https://someplaceholder.com"/>
</ng-template>
containsProfileImage(): boolean{
let returnVal = false;
this.user.images.forEach(image => {
if (image.isProfileImage) {
returnVal = true;
return;
}
}
return returnVal;
}
編輯:替代解決方案
正如Chris G作為回應所說的那樣。 您還可以通過具有個人資料圖像的圖像過濾您的圖像。 通過這種方式,您可以檢查過濾后的數組中是否至少有一個圖像。 如果沒有,請顯示noImage
ngTemplate。
<ng-container *ngIf="user.images.length">
<ng-container *ngIf="filteredImagesLength; else noImage">
<div *ngFor="let image of images">
<img
*ngIf="image.isProfileImage"
[src]="image.path"
/>
</div>
</ng-container>
</ng-container>
<ng-template #noImage>
<img src="https://someplaceholder.com"/>
</ng-template>
get filteredImagesLength(): number {
return user.images.filter(i => i.isProfileImage)?.length;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.