rafon
rafon

Reputation: 1542

Angular - Dynamic ngModel for inputs

How can I have a dynamic model for a form element (i.e. input, select)?

I have this:

<input type="text" [name]="input.name" [(ngModel)]="input.name" [title]="input.title" /> 

wherein the model could be anything (i.e. address, first_name) as it is generated dynamically?

export class SampleComponent implements OnInit {

    inputs!:any[];

    constructor() { }

    ngOnInit(): void {

        console.log(this.inputs);

    }

}

I looked for relevant questions this one being the closest Set a dynamic property in ngModel inside ngFor, with Angular 2, but I can seem to do the trick. Is there another way to achieve this?

Angular version: (12.0.2)

Thanks in advance!enter code here

Upvotes: 0

Views: 1341

Answers (2)

satyen
satyen

Reputation: 109

#I guess you might look at this
https://angular.io/guide/forms#bind-input-controls-to-data-properties

#import FormsModule

#create a template driven form
<form #myForm="ngForm">
<input type="text" class="form-control" id="name"
               required
               [(ngModel)]="input.name" name="input.name"
[title]="input.title"
               #name="ngModel">
<!-- for example -->
<select class="form-control" id="cities"
                required
                [(ngModel)]="model.city" name="cities"
                #cities="ngModel">
          <option *ngFor="let data of data" [value]="data">{{data}}</option>
        </select>
</form>
# here #cities, #name is just template ref variable can be used or avoided in case you don't need to track control of model

Upvotes: 1

TotallyNewb
TotallyNewb

Reputation: 4790

You would be much better off using Reactive Forms instead of Template Driven forms to achieve this task, since it gives you more flexibility, ease of use when it comes to dynamic validators and multiple working examples (including this one on the official docs).

Since your model has any type, this pretty much answers your question - no need to repeat the official docs in my opinion (though there are multiple other valid examples if you google "angular dynamic form".

Upvotes: 1

Related Questions