Angular ngFor变量赋值

标签 angular angular5

我有以下内容:

<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/

相关文章:

angular - 异常 : Root segment cannot have matrix parameters

javascript - 该运算符未定义有什么问题

javascript - 如何减少对现有 Angular 5 元素的添加

angular - 如何动态添加和删除 Angular 5 中的表行和列?

node.js - NodeJS 渲染 html 文件,其表单在 Angular 侧不起作用

javascript - Angular/HTML - 将显示完整的 JSON 但不能仅显示单个属性

angular - 动态更改 ionic 菜单侧

javascript - 使用组件 Angular - TypeScript 处理表单错误

node.js - 错误: EBUSY: resource busy or locked, rmdir

angular5 - ngxs、redux 开发工具显示以前的状态