获取数组中第一项的 属性(如果存在)
Get property of first item in array if exists
在Angular 7 我有型号:
export interface ProductModel {
files: FileModel[];
name: string;
}
export interface FileModel {
type: string;
url: string;
}
在给定产品的模板上,我需要显示类型为 "image":
的第一个文件的 url
{{ product.files.find(x => x.type == 'image').url }}
但我收到错误:
Bindings cannot contain assignments
如何操作?
备注
我不确定 product.files.find(x => x.type == 'image')
returns 任何项目。
一开始就这样做确实是个坏主意。每次运行更改检测时,此查找调用都会 re-executed。这会拖累页面的性能,甚至可能变得无法使用。首选方法是将值分配给 属性 并改为绑定到此 属性。
imageUrl : string;
findProd() {
this.imageUrl = product.files.find(x => x.type == 'image').url
}
并在模板中
{{ imageUrl }}
在 Angular 绑定中使用表达式是不好的做法。我建议将你的表达式移动到一个变量中:
myItem: string = this.productModel.files.find(x => x.type == 'image').url;
还有你的html:
{{ myItem }}
看看 this StackBlitz 演示。
在您的代码中:
getProd() {
return product.files.find(x => x.type == 'image').url
}
模板:
{{ getProd() }}
在Angular 7 我有型号:
export interface ProductModel {
files: FileModel[];
name: string;
}
export interface FileModel {
type: string;
url: string;
}
在给定产品的模板上,我需要显示类型为 "image":
的第一个文件的 url{{ product.files.find(x => x.type == 'image').url }}
但我收到错误:
Bindings cannot contain assignments
如何操作?
备注
我不确定 product.files.find(x => x.type == 'image')
returns 任何项目。
一开始就这样做确实是个坏主意。每次运行更改检测时,此查找调用都会 re-executed。这会拖累页面的性能,甚至可能变得无法使用。首选方法是将值分配给 属性 并改为绑定到此 属性。
imageUrl : string;
findProd() {
this.imageUrl = product.files.find(x => x.type == 'image').url
}
并在模板中
{{ imageUrl }}
在 Angular 绑定中使用表达式是不好的做法。我建议将你的表达式移动到一个变量中:
myItem: string = this.productModel.files.find(x => x.type == 'image').url;
还有你的html:
{{ myItem }}
看看 this StackBlitz 演示。
在您的代码中:
getProd() {
return product.files.find(x => x.type == 'image').url
}
模板:
{{ getProd() }}