问题
I want to take some config object to show some nested data.Here is the demo code
As it can be seen, "customer.something"
is what I need to access. Now there could be 'N'level of nesting . The grid takes care of it using field='customer.something'
. How to do the same using my template
<e-column field='customer.something' headerText='Other' editType='dropdownedit' [edit]='editParams' width=120>
Here is the HTML file:
<ejs-grid #Grid [dataSource]='data' allowSorting='true'>
<e-columns>
<ng-template #colTemplate ngFor let-column [ngForOf]="colList">
<e-column [field]='column.field' [headerText]='column.header' textAlign='Right' width=90>
<ng-template #template let-data>
{{data[column.field] | currency:'EUR'}} <-- want to fix this line
</ng-template>
</e-column>
</ng-template>
</e-columns>
</ejs-grid>
<!-- <ejs-grid #Grid [dataSource]='data' allowSorting='true'>
<e-columns>
<e-column field='price' isPrimaryKey='true' headerText='Price' textAlign='Right' width=90></e-column>
<e-column field='customer.something' headerText='Other' editType='dropdownedit' [edit]='editParams' width=120>
</e-column>
</e-columns>
</ejs-grid> -->
回答1:
You could use a pipe to get the field value by the string path. Like this:
@Pipe({name: 'fieldFromPath'})
export class FieldFromPathPipe implements PipeTransform {
transform(data: Object, property: string): Object {
property = property.replace(/\[(\w+)\]/g, '.$1');
property = property.replace(/^\./, '');
var a = property.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in data) {
data = data[k];
} else {
return;
}
}
return data;
}
}
and on the template:
<ng-template #template let-data>
{{data | fieldFromPath: column.field | currency:'EUR'}}
</ng-template>
Here's how it would look:
https://stackblitz.com/edit/angular-ej2syncfusion-angular-grid-jqm2kz
PS: I got the function to get the property value from the string path from this stackoverflow answer: Accessing nested JavaScript objects and arrays by string path
There are other ways to get it, maybe some is better.
来源:https://stackoverflow.com/questions/64911518/access-nested-object-with-n-level-deep-object-using-square-bracket-notation