angular - 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}}'">
解决方案
问题是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 对象。
希望能帮助到你
推荐阅读
- here-api - 传递参数以在 HERE 反向地理编码中获取最近的道路名称或建筑物名称
- python - 在 python 中打印一个直角三角形,从输入 n 开始,行 n
- c++ - 使用模板特化来比较指针引用
- amazon-ec2 - 将 Cloudflare CNAME 指向 AWS ALB 会导致错误 522
- javascript - 如何制作一个无限的 JS 轮播(无穷大问题)
- c++ - 我是 C++ 新手,有没有一种算法可以在 3d 数组中找到最接近 0 的距离?
- cordova - 可以用 Dart 创建一个 Cordova 插件吗?
- c# - 指针类型上的 FieldInfo.GetValue 与调试器报告的值不匹配
- javascript - 使用 next.js 创建快速服务器时出现 EADDRINUSE 错误
- r - 如何获取以“.nc”结尾的不同长度的字符串的最后一部分