shiji
shiji

Reputation: 79

How to define ngmodel name dynamically?

Here is my code:

vmarray[]={'Code','Name','Place','City'}
export class VMDetail {

    lstrData1:string;
    lstrData2:string;
    lstrData3:string;
    lstrData4:string;
    lstrData5:string;
    lstrData6:string;
    lstrData7:string;   
}

vm:VMDetail


<ng-container *ngFor="let datas of vmarray;  let i = index;"> 
    <mat-form-field class="example-full-width" [ngStyle]="ngStyleMapper(datas.width)">    
        <input [(ngModel)]="vm.lstrData{{i}}"   name="vm.lstrData{{i}}"  matInput placeholder ={{datas}}  (click)="dblclick(i)">
    </mat-form-field>        
</ng-container> 

How can I define ngModel name dynamically?

Upvotes: 1

Views: 79

Answers (2)

amd
amd

Reputation: 21482

You are looking for the array data structure.

A simple approach would be to create another array for values and link each field with its value according to the array index.

@Component({
    template: `
        <pre>{{ values | json }}</pre>
        <ng-container *ngFor="let field of fields; let i = index;">
            <input [name]="'field_' + i" [(ngModel)]="values[i]" />
        </ng-container>
    `,
})
class MyComponent {

    fields = ['Code', 'Name', 'Place', 'City'];

    values: string[] = [];
}

Advantages

  • more readable and easy to maintain (adding more fields is as simple as adding the field in the fields array)
  • no need to introduce another data type (in your case VMDetail)

Upvotes: 0

Igor
Igor

Reputation: 62238

You can access the object member using an indexer

[(ngModel)]="vm['lstrData'+i]"

Upvotes: 3

Related Questions