我有帶有預覽的影像檔案上傳輸入,用于顯示上傳的影像檔案。在那里我需要處理一些條件,如下所示:
- 如果未選擇影像檔案且資料庫沒有影像,則顯示默認影像,否則根據影像顯示
- 如果資料庫有影像顯示在預覽然后選擇檔案上傳后然后在預覽中顯示上傳的檔案
我不知道如何處理srcimg 標簽上的這些條件。
有角度的html代碼
<div >
<div >
<img [src]="url?url:defaultUserProfileUrl" alt="以角度上傳影像檔案" >
</div>
<div >
<div >
<input type="file" id="myfile" name="myfile" [formControl]="profile_image" [(ngModel)]="currentInput"
accept='image/*' (change)="onFileSelected($event)" />
</div>
</div>
</div>
如果存在資料庫影像,則顯示如下:
<img [src]="userdata.profile_path?userdata.profile_path:defaultUserProfileUrl" alt="以角度上傳影像檔案" />
角度 ts 代碼
url: any = [];
defaultUserProfileUrl:string = 'assets/images/default_user_profile.png';
onFileSelected(event) {
console.log(event.target.files[0]);
this.currentInput = event.target.files[0];
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event) => {
this.url = event.target.result;
};
}
}
我如何處理影像中的多個/嵌套 if else 條件src?或者有沒有其他解決方案?
請指導和幫助。提前致謝。
uj5u.com熱心網友回復:
你已經定義了一個變數 defaultUserProfileUrl:string = 'assets/images/default_user_profile.png';
現在定義一個變數為 activeImageUrl = defaultUserProfileUrl:string
并且在 ngOnInit() 內部進行后端呼叫以檢索存盤在資料庫中的影像(如果有)并將 activeImageUrl 替換為檢索到的影像。
在 html 中
<img [src]="activeImageUrl" alt="以角度上傳影像檔案" >
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316373.html
