我有以下内容:
<div *ngFor="let item of order.items">
我需要显示结果,例如:
{{item.product.category.availability.selected.name.value}}
{{item.product.category.availability.selected.id.value}}
理想情况下,我想将整个部分分配给模板中的一个变量:
let item = item.proproduct.category.availability.selected
所以我可以在整个模板中显示这样的数据(更短的方式):
{{item.name.value}}
{{item.id.value}}
有办法吗?
最佳答案
解构特性在 Angular 模板中不可用。检查 git hub 中的问题 repository
一个解决方案是创建一个管道来格式化它。例如:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'formatValues'})
export class FormatValues implements PipeTransform {
//Destructuring in the first parameter which has the item value
transform({ product: { category: { availability: { selected :{ name: { value } } } } } }: any, args?: any[]): string {
return value;
}
}
导入并在模块中声明:
import { FormatValues } from './values.pipe';
@NgModule({
declarations: [
AppComponent,
FormatValues
],
...
})
最后使用管道:
<div *ngFor="let item of order.items">
{{item | formatValues}}
</div>
此外,如果您想阻止管道,只需在组件中创建一个函数并调用它:
{{formatValue(item)}}
在你的 ts 中:
formatValue({product:{ category:{availability:{selected:{ name:{ value }}}}}}: any): string {
return value;
}
关于Angular ngFor变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53964149/