首页 > 解决方案 > Angular 理解属性绑定

问题描述

假设我在 ts 文件中有这个:

  arrImages = ['Front', 'Back', 'Left', 'Right'];
  Front = "...";
  Back = "...";
  Left = "...";
  Right = "...";
  ChangeImage(pImageView) {
      console.log(pImageView)
  }

这在 html 文件中:

<ng-container *ngFor="let Item of arrImages">
    <label>{{Item}}</label>
    <img src="{{Item}}">
    <button (click)="ChangeImage(Item)">Change</button>
</ng-container>

标签显示为<label>Front</label><label>Back</label>等。这是正确的。

按钮<button (click)="ChangeImage('Front')">Change</button>或等方式出现<button (click)="ChangeImage('Back')">Change</button>。这是正确的。

但是我如何让img<img [src]="Front">or的形式出现<img [src]="Back">?因为我无法让图像 src 与 ts 变量链接。我尝试了所有这些:

<img src="Item">
<img src="{{Item}}">
<img [src]="Item">
<img [src]="'Item'">
<img [src]="{{Item}}">
<img [src]="'{{Item}}'">

标签: angulartypescript

解决方案


问题是arrImages仅包含不正确图像路径的字符串。

处理这个问题的两种方法:


第一种方式 - 自定义管道

将项目更改arrImages为有效的图像路径,例如:

arrImages = ['Front.png', 'Back.png', etc...] (您可以删除其他变量)

然后,制作一个自定义管道以从图像路径中提取图像名称

@Pipe({
  name: 'extractednamefromfilepath'
})

export class ExtractNameFromFilePathPipe implements PipeTransform 
{
  transform(val:string) : string 
  {
    // Split full path into small chunks of path (img/image.png => ['img', 'image.png']
    var splittedPath = value.split('/');

    // Sub the 4 last char of the last splittedPath chunk ('image.png' => 'image')
    return splittedPath[splittedPath.length - 1]
          .substring(splittedPath[splittedPath.length - 1].length - 4);
  }
}

并以这种方式使用它

<ng-container *ngFor="let Item of arrImages">
    <label>{{Item | extractnamefromfilepath}}</label>
    <img src="{{Item}}">
    <button (click)="ChangeImage(Item)">Change</button>
</ng-container>

在 ChangeImage 函数中,Item 现在将是图像的路径,但您可以使用类似于管道的函数从路径中提取名称。


第二种方式 - 类

制作一个像

export class ImageHolder 
{
    imgPath: string;
    imgName: string;

    constructor(imgPath: string)
    {
        this.imgPath = imgPath;
        imgName = extractNameFromPath(imgPath);
    }

    extractNameFromPath(imgPath: string) : string
    {
        // Split full path into small chunks of path (img/image.png => ['img','image.png']
        var splittedPath = value.split('/');

        // Sub the 4 last char of the last splittedPath chunk ('image.png' => 'image')
        return splittedPath[splittedPath.length - 1]
              .substring(splittedPath[splittedPath.length - 1].length - 4);
    }
}

然后让你的数组像

arrImgs = [];
arrImgs.push(new ImageHolder('Front.png'), new ImageHolder('Back.png'), etc..);

并像使用它一样

<ng-container *ngFor="let Item of arrImages">
    <label>{{Item.imgName}}</label>
    <img src="{{Item.imgPath}}">
    <button (click)="ChangeImage(Item.)">Change</button>
</ng-container>

在 ChangeImage 函数中, item 现在是一个ImageHolder 对象

希望能帮助到你


推荐阅读