-1

How to create element with dynamic name in ngModel?

 <div class="form-group" *ngFor="let setting of settings">
    <label [for]="setting.name + '-' + setting.type">Setting</label>
    <input type="number" class="form-control"
           [id]="setting.name + '-' + setting.type"
           [name]="setting.type + '_typeInterval'"
           [(ngModel)]="setting.timeInterval"
           required #"{{setting.type + '_typeInterval'}}"="ngModel">
    <div class="errors-area" *ngIf="setting.type + '_typeInterval'".errors">
        <span *ngIf="setting.type + '_typeInterval'".errors.required">Required</span>
    </div>
</div>

How to make it so that a variable of type ngModel can be assigned a name dynamically? In this case, setting.type + '_typeInterval'.

tmoha
  • 1
  • 3

1 Answers1

0

You can use the array notation, with the this keyword, as shown in this stackblitz :

<input type="text" [(ngModel)]="this['someVar']">
<input type="text" [(ngModel)]="this[some + Var]">
  • Not certainly in that way. I need a dynamic name, which will appear in code in #. #"{{setting.type + '_typeInterval'}}" – tmoha Feb 11 '19 at 11:26
  • If you want a reference to your control instead of dynamically naming your `ngModel` like I've shown you, consider using [`FormControl`](https://angular.io/api/forms/FormControl), which is made for that. –  Feb 11 '19 at 11:28