【问题标题】:trying to use [src] with url and variable尝试将 [src] 与 url 和变量一起使用
【发布时间】:2019-04-16 10:44:21
【问题描述】:

在我的 component.ts 文件中,我有一个用户列表。我想在我的 html 中显示它们。

component.html

   <ul>
     <li *ngFor="let user of users" class="contact-details">
       <img [src]="'https://app.compnay.com/{{user.profileImage}}' === ''? '../../../../../../../assets/images/empty-user-profile.png': 'https://app.company.com/{{user.profileImage}}'">
     </li>
   </ul>

我收到了这个错误

未捕获的错误:模板解析错误:解析器错误:得到插值 ({{}}) 其中表达式应位于第 29 列 ['https://app.company.com.sa/{{user.profileImage}}' === ''? '../../../../../../../assets/images/empty-user-profile.png': 'https://app.company.com.sa/{{user.profileImage}}'] 在 ng:///ChatModule/ContactSearchResultListComponent.html@6:19 ("ass="contact-image">

【问题讨论】:

  • 仅供参考,'https://app.compnay.com/{{user.profileImage}}' 永远不能是 ''。也许您只想检查user.profileImage === ''
  • 如果没有 url,else 条件将如何呈现?
  • 查看 Vitalii 的回答,但条件一开始是错误的,与 else 部分无关。
  • 是的,正如@FedericoklezCulloca 所说,条件是错误的。它与 Angular 模板引擎有关,而不是您的代码本身。您不能在 1 个语句中同时使用模板绑定和插值。

标签: html angular


【解决方案1】:

由于您已经通过[src] 使用Angular 模板绑定,因此无需使用插值{{}},这就是您不允许使用并出现错误的原因。

正确的语法是:

    <img [src]="user.profileImage === '' ? '../../../../../../../assets/images/empty-user-profile.png': 
   'https://app.company.com/' + user.profileImage">

但我鼓励您将该逻辑移至 component.ts 并简单地绑定变量,例如

HTML

<img [src]="userProfileImage" />

TS

userProfileImage: string;

ngOnInit(): void {
   ...

   this.userProfileImage = user.profileImage === '' ? '../../../../../../../assets/images/empty-user-profile.png': 
   'https://app.company.com/' + user.profileImage;

   ...
}

【讨论】:

  • 非常感谢。这很好,但是如果没有图像我仍然找不到错误,应该用 else 条件中提供的空图像替换它
  • 你能检查一下 user.profileImage 的值是多少吗?
  • 总有一个值但不是总能找到,该值为profileImage: "/bea/attachment/stcuserimages/999999.jpg"
  • 您无法仅通过将其与空字符串进行比较来预测是否会找到它。这里需要复杂的解决方案。我建议在组件中使用 AJAX 请求查询图像,并在错误响应中捕获 404。如果发生这种情况,则意味着您无法加载图像。
【解决方案2】:

这样使用

<ul>
  <li *ngFor="let user of users" class="contact-details">
    <img [src]="user.profileImage === '' ? '../../../../../../.../assets/images/empty-user-profile.png' : 'https://app.company.com/' + user.profileImage ">
</ul>

【讨论】:

    【解决方案3】:

    就这样试试

    <ul>
      <li *ngFor="let user of users" class="contact-details">
        <img [src]="user.profileImage === ''?'../../../../../../../assets/images/empty-user-profile.png':'https://app.company.com/'+user.profileImage">
      </li>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 2012-11-22
      • 2023-03-10
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多