简体   繁体   中英

Angular - Dynamic ngModel for inputs

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

I have this:

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

wherein the model could be anything (ie 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

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" .

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM