Using Angular 4, I have to create a dynamic Input field where users can add and remove input fields.
But I am getting an issue where the same ngModel is getting assigned to all input fields and Set input fields reset on add or remove button.
<h3> Dynamic Input </h3>
<form (ngSubmit)="SubmitFnc($event)">
<div *ngFor="let ItmVar of inputAryVar; let IdxVar=index" [attr.Idx]="IdxVar">
<input type="text" name="field1" placeholder="Name Field"
[(ngModel)]="ItmVar.nameLbl"> 
<button type="button" (click)="addDelBtnFnc(ItmVar,IdxVar)">
{{ IdxVar == inputAryVar.length - 1 ? "[ + ]" : "[ - ]"}}
</button>
</div>
<button > Submit </button>
</form>
export class AppComponent {
inputAryVar:any
constructor() { }
ngOnInit(){
this.inputAryVar=[
{
"nameLbl":"Field1"
},
{
"nameLbl":"Field2"
},
{
"nameLbl":"Field3"
}
]
}
addDelBtnFnc(itmVar, idxVar)
{
if(idxVar==this.inputAryVar.length-1)
{
this.inputAryVar.push({
nameLbl:"Field"+(this.inputAryVar.length+1)
})
console.log(this.inputAryVar)
}
else
this.inputAryVar.splice(idxVar,1)
}
SubmitFnc(event)
{
console.log(this.inputAryVar)
}
}
The Code I tried is on Stackblitz
Not able to figure out why ngModel is not getting set properly.
That is because all the input fields are getting the same value for name
attribute. Assign unique name
to each input field.
<input type="text" name="field_{{IdxVar}}" placeholder="Name Field"
[(ngModel)]="inputAryVar[IdxVar].nameLbl">
Fixed stackblitz