How to use dynamic variables in ngModel?
I am trying to use the code below but the following error appears:
<div *ngFor="let num of ['1','2','3']; let i=index">
<input id="qtd{{num}}" [(ngModel)]="qtd{{num}}" type="text"/>
</div>
Erro
Unhandled Promise rejection: Template parse errors:
Parser Error: Got interpolation ({{}})
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
NgModel is a directive that creates the FormControl instance from a domain model and binds it to a form control element. It uses two kinds of binding: Property binding.
To fix Can't bind to 'ngModel' since it isn't a known property of 'input' error in Angular applications we have to import FormModule in app. module. ts file. If you are using FormBuilder class to create reactive form we have to import ReactiveFormsModule as well to avoid below error.
NgModel is used to create a top-level form group Instance, and it binds the form to the given form value. NgModule: Module used by NgModel is: FormsModule.
Define array in component and keep pushing in it.
export class AppComponent {
qtd:any[] = {};
}
Then, update your template like
<div *ngFor="let num of ['1','2','3']; let i=index">
<input id="qtd{{num}}" [(ngModel)]="qtd[num]" type="text"/>
</div>
{{ qtd | json}}
In this all your dynamic models will be in qtd array
Plunker
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With