【问题标题】:how to create custom pipe for images?如何为图像创建自定义管道?
【发布时间】:2019-10-10 05:25:17
【问题描述】:

我创建了一个返回用户配置文件的 Angular 应用程序。这些个人资料有时有个人资料图片,有时没有

如果个人资料图片为空,我想使用管道显示占位符图片

我想将用户图像发送到管道并检查它是否为空,将其替换为assets/images/user.jpg,否则保留用户图像

empty-profile-image.pipe.ts

 import { Pipe, PipeTransform } from '@angular/core';

 @Pipe({
 name: 'emptyProfileImage'
 })

 export class EmptyProfileImagePipe implements PipeTransform {

    transform(contactImage: string): string {
    if (contactImage == ''){
      return "assets/images/user.jpg"
    }
    else{
      return "groupMember.contactImage";
    }
    }

 }

user-profile.component.ts

  <img class="user-image"
   src=" user.contactImage | emptyProfileImage">

【问题讨论】:

    标签: angular pipe


    【解决方案1】:

    试试类似的东西

    import { Pipe, PipeTransform } from '@angular/core';
    
     @Pipe({
     name: 'emptyProfileImage'
      })
     export class EmptyProfileImagePipe implements PipeTransform {
    
      transform(contactImage: string): string {
         return contactImage || yourplaceholderimagepath;
       }
     }
    

    然后在你的html中

     <img class="user-image"
       [src]=" user.contactImage | emptyProfileImage">
    

    注意它应该是[src] 而不是src

    demo

    【讨论】:

    • 它在第一次工作但当我重新加载页面时出现错误“找不到管道'emptyProfileImage'”
    • 你可以为你的问题创建 stackblitz 演示
    • @RenadMunhi 那么有什么问题吗?如果它对你有用,请你投票并标记为 ans
    • 有时我会得到像 /bea/attachment/userimages/.jpg 或 /bea/attachment/userimages/userID.jpg 这样的图像 url,用户 ID 可以是 1234 、 8975。当我在使用之前检查 html 时管道我刚刚做了 contactimage === " '' ? placeholderimagepath 但现在当我使用管道时它不再工作了
    • 不是错误,是条件不对,空图片没有被占位符替换
    【解决方案2】:

    设置日期图片路径为

    <img [src]="user.contactImage | emptyProfileImage" >
    

    与返回的管道函数一样

    return contactImage || "assets/images/user.jpg";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多