Home > database >  Angular dynamic nested key ngModel
Angular dynamic nested key ngModel

Time:07-26

How to use dynamic key in ngModel? I am using the primeNg library and i'm trying to bind a dynamic key to the ngModel

this is the html template

<p-table [columns]="cols" [value]="data">
  <ng-template pTemplate="body" let-rowData let-columns="columns">
    <tr>
      <td *ngFor="let col of columns">
        <input type="text" pInputText [(ngModel)]="rowData[col.field]"/>
      </td>
    </tr>
  </ng-template>
</p-table>

this is the "cols" variable

cols = [
      { field: 'variables.code', header: 'Code' },
      { field: 'variables.name', header: 'Name' },
];

and this is an example of data

[{
  "variables": {
     "code": "D44D5",
     "name": "keyboard"
  }
}]

CodePudding user response:

You can do something like below, where you can split col.field.split('.') as fieldName and then form ngModel like this rowData[fieldName[0]][fieldName[1]].

<div *ngFor="let rowData of rows;">
  <div *ngFor="let col of columns;">
    <ng-container *ngIf="getValue(rowData, col.field) as fieldName">
      <input type="text" [(ngModel)]="fieldName" />
    </ng-container>
  </div>
</div>

TS

getValue(rowData, fieldPath) {
    const fieldName = fieldPath
      .replace(/[\[\]'] /g,'.')
      .split('.')
      .filter(i => i);
    console.log(fieldName);
    const field = fieldName.reduce((acc, f) => acc[f], rowData)
    return field;
}

Stackblitz

Note:- Above would work for both the usecases, when object has nested structure.

  • Related