Lando
Lando

Reputation: 1

Dynamic binding ngModel in ngFor loop

I'm trying to create an angular dialog that will dynamically create inputs based on the keys of a given object. My main problem is binding [(ngModel)], in the end it should be something like [(ngModel)]="data.id".

Dialog Box html:

<h1 mat-dialog-title>Add Customer </h1>
<div mat-dialog-content>

  <mat-form-field *ngFor="let item of myKeys; let index = index; trackBy:index;" >
    <input matInput
      type="string"
      name={{item}}
      placeholder={{item}}
      [(ngModel)]="data.item"  
      >
  </mat-form-field>

</div>

You chose: <i>{{data.name}}</i>

<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>
</div>e

Dialog Box angular component ts:

@Component({
  selector: 'app-dialog-edit',
  templateUrl: './dialog-edit.component.html',
})
export class DialogBoxEditComponent {
  test = [
    'data.id',
    'data.name',
    'data.address',
    'data.city',
    'data.payment'
  ];

  myKeys = this.getMyKeys(this.data);

  @Output() editMode = new EventEmitter();

  constructor(
    public dialogRef: MatDialogRef<DialogBoxEditComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) {}

  onNoClick(): void {
    this.dialogRef.close();
  }
  getMyKeys(myData) {
    return Object.keys(myData);
  }
  getType(myIn) {
    return typeof(myIn);
  }
  getty(mytest) {
    return 'data.' + mytest;
  }
}

what I've tried:

[(ngModel)]="data.item" results in all inputs sharing data.id as the one ngModel

[(ngModel)]="test[index]" Here I tried creating an array in the component that would return the desired binding, this however fills in the test array value into the input field, but no binding is made

[(ngModel)]="test.item" Instead of an array, here test is an object. This also results in a singular shared binding link the first example. (see picture below)

dialog with shared binding

Anything would be appreciated.

Upvotes: 0

Views: 2226

Answers (1)

Jimmy
Jimmy

Reputation: 11

<mat-form-field *ngFor="let item of myKeys; let index = index; trackBy:index;" >
  <input matInput type="string"
    name={{item}} placeholder={{item}}
    value = {{ data[item] }} #foo>
</mat-form-field>

Add #foo to input, this will bind #foo to each element and your ng-models wont share....

Upvotes: 0

Related Questions