首页 > 解决方案 > 在 HTML 上显示数据的 If Else 语法

问题描述

我正在尝试在图像上传递 alt 文本值,这是代码:

 <img *ngIf="document.story_image_1 " [src]="document.story_image_1 " class="image-1" alt="{{document.image_alttxt | 'default alt text'}}"  />

对于alt属性,如果值为空,我希望它有一个默认的替代文本。请建议使用 if else 语句显示数据的正确语法是什么。

标签: javascripthtmlangular

解决方案


您应该使用逻辑 OR 而不是按位 OR

alt="{{document.image_alttxt || 'default alt text'}}"

如果可以的话,您也可以使用可选链接 ( ?.)documentundefined

alt="{{document?.image_alttxt || 'default alt text'}}"

推荐阅读