Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Dynamic Variables in ngModel

Tags:

angular

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 ({{}})

like image 588
rafaelcb21 Avatar asked Dec 17 '16 13:12

rafaelcb21


People also ask

How[( ngModel)] works?

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.

Is ngModel property binding?

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.

Can't bind to ngModel since it isn't a known property of input Ng?

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.

Which module is required for ngModel?

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.


1 Answers

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!

like image 143
Ashok Shah Avatar answered Oct 18 '22 08:10

Ashok Shah