I currently have an ion-input that is going through a *ngFor so it repeats multiple times. When I want to add a new record (to add a new ion-input row) to the *ngFor loop, there is an error for:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'model: abc'. Current value: 'model: '.
Here are my codes:
.html
<ion-item *ngFor="let item of values; let i = index;">
<ion-input formControlName="taskDetail" [(ngModel)] = "values[i].answer" type="text"></ion-input>
<ion-icon name="remove-circle" (click)="removeTaskOption(i)" slot="end"></ion-icon>
</ion-item>
.ts
checklistCounter = [];
values = [];
constructor() {
this.checklistCounter = Array(this.numCounter).fill(1).map((x, i) => i + 1);
for (let i = 0; i < this.checklistCounter.length; i++) {
let data = {
id: i,
answer:''
}
this.values.push(data);
}
}
addNewTaskOption(){
let data = {
id: (this.values[this.values.length - 1].id + 1),
answer:''
}
this.values.push(data);
}
removeTaskOption(i:number){
this.values.splice(i, 1);
}
Here are some images for your reference:
Image of Original UI (Before clicking on add or remove ion-input rows):
Image of UI (After typing in 'abc' into the first ion-input then click on the add button:
Image of the error:
What I am trying to achieve is even though the user has typed in something in the ion-input fields, if they want to add more fields, the fields will just appear below the original fields. I've read other solutions but all of them subscribe to a service and the solutions are for that, so I don't think I can apply it to my case. Please help!
UPDATE: Managed to solve the problem by following @GaurangDhorda's answer.
Codes:
.html
<ion-item *ngFor="let item of values; let i = index;">
<ion-input formControlName="taskDetail" [value]="item.answer" (change)="setQuantity($event.target.value, i)" type="text"></ion-input>
<ion-icon name="remove-circle" (click)="removeTaskOption(i)" slot="end"></ion-icon>
</ion-item>
.ts (Added in new method)
setQuantity(ev:string, i:number){
this.values[i].answer = ev;
}
[(ngModel)] = "values[i].answer"
with[(ngModel)] = "item.answer"
– Sergey