Angular 变量赋值的角度变换

Angular 变量赋值的角度变换,angular,angular5,Angular,Angular5,我有以下资料: <div *ngFor="let item of order.items"> 理想情况下,我希望将整个部分分配给模板中的一个变量: let item = item.proproduct.category.availability.selected 因此,我可以在整个模板中显示这样的数据(更短): 有办法做到这一点吗? <div *ngFor="let item of order?.items?.product?.category?.availability?

我有以下资料:

<div *ngFor="let item of order.items">
理想情况下,我希望将整个部分分配给模板中的一个变量:

let item = item.proproduct.category.availability.selected
因此,我可以在整个模板中显示这样的数据(更短):

有办法做到这一点吗?


<div *ngFor="let item of order?.items?.product?.category?.availability?.selected
"> 
你可以这样写

现在您可以访问

{{item.name.value}
{{item.id.value}

不能在Angular中的模板中定义这样的速记变量

我能想到的最近的事情

<div *ngFor="let item of order.items">
    <ng-container *ngIf="item.product.category.availability.selected as value">
         ...
       {{value}}
         ...
    </ng-container>
</div>
模板:

<div *ngFor="let item of order.items">
...
{{getNestedProperty(item)}}
...
</div>

...
{{getNestedProperty(项)}
...
其他人建议创建一个子组件,这似乎也是一个好主意


角度模板中没有分解功能。检查git中心中的问题

一种解决方案是创建一个管道来格式化此文件。例如:

{{item.product.category.availability.selected.name.value}}
{{item.product.category.availability.selected.id.value}}
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>
在您的ts中:

formatValue({product:{ category:{availability:{selected:{ name:{ value }}}}}}: any): string {
  return value;
}

您可以创建一个组件并将值作为输入传递给该组件:
这会更改原始功能,因为
*ngFor
不再迭代
order.items
数组。
<div *ngFor="let item of order.items">
   {{item | formatValues}}
</div>
{{formatValue(item)}}
formatValue({product:{ category:{availability:{selected:{ name:{ value }}}}}}: any): string {
  return value;
}