I have a list of object like this:
listSubject = [
{name: 'Math', lessonPerWeeks: 1},
{name: 'Lit', lessonPerWeeks: 2},
{name: 'Bio', lessonPerWeeks: 3},
{name: 'Phy', lessonPerWeeks: 7},
{name: 'Remains', lessonPerWeeks: 36},
];
I put them in a loop of input for changing values like this:
<div *ngFor="let subject of listSubject">
<input *ngIf="subject.name != 'Remains'" type="number" [(ngModel)]="subject.lessonsPerWeeks" [formControl]="changeValue">
<div *ngIf="subject.name === 'Remain'">
{{subject.lessonPerWeeks}}
</div>
</div>
The FormControl: changeValue is used to detect the changes from input to recalculate the percent of each subject over totals:
this.changeValue
.valueChanges
.debounceTime(200)
.subscribe(()=>{
for(let i=0; i < this.listSubject.length;i++){
let subject = this.listSubject[i];
let lastSubject = this.listSubject[this.listSubject.length-1];
subject.percentSem1 = subject.lessonPerWeeks/ this.totalLessonPerWeeks * 100;
if(i === this.listSubject.length - 1){
return;
}
else if(i === 0){
lastSubject.lessonPerWeeks = 36;
}
lastSubject.lessonPerWeeks -= subject.lessonPerWeeks;
}
});
Everything works fine except the initial display value in the Inputs.
All inputs display the value of the last item on the list. In this case, the value of all inputs is 7 instead of different value. If I remove the [formControl] , all data display exactly
Here is the screenshot:
Multi Input display
I think my problem is use a FormControl for all the input. Please help me to solve this problem. Thank you