0

我有一个这样的对象列表:

listSubject = [
{name: 'Math', lessonPerWeeks: 1},
{name: 'Lit', lessonPerWeeks: 2},
{name: 'Bio', lessonPerWeeks: 3},
{name: 'Phy', lessonPerWeeks: 7},
{name: 'Remains', lessonPerWeeks: 36},
];

我将它们放在一个输入循环中以更改如下值:

<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>

FormControl:changeValue 用于检测输入的变化,以重新计算每个主题占总数的百分比:

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;
          }

        });

除了输入中的初始显示值外,一切正常。所有输入都显示列表中最后一项的值。在这种情况下,所有输入的值为 7 而不是不同的值。如果我删除 [formControl] ,所有数据都显示完全这是截图:多输入显示 在此处输入图像描述

我认为我的问题是对所有输入使用 FormControl。请帮我解决这个问题。谢谢

4

2 回答 2

0

阅读@Partha Sarathi Ghosh 的回答和评论后。我终于找到了解决方案。我为列表中的每个对象添加了相同的 FormControl,然后将它们绑定到 HTML 中。打字稿代码:

this.listSubject.forEach((subject)=>{
      subject.changeValue = new FormControl();
      subject.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;
      }

    });}

和 HTML

<div *ngFor="let subject of listSubject">
<input *ngIf="subject.name != 'Remains'" type="number" [(ngModel)]="subject.lessonsPerWeeks" [formControl]="subject.changeValue">
<div *ngIf="subject.name === 'Remain'">
   {{subject.lessonPerWeeks}}
</div>
</div>

但是,有没有更好的解决方案?

于 2017-03-20T07:26:01.800 回答
0

使用 name 属性作为每个输入的唯一属性。否则,循环中的输入字段始终显示最后一项数据的值。

<div *ngFor="let subject of listSubject; let i = index">
<input *ngIf="subject.name != 'Remains'" 
 type="number" name="field_{{i}}" 
 [(ngModel)]="subject.lessonsPerWeeks" [formControl]="changeValue">
<div *ngIf="subject.name === 'Remain'">
   {{subject.lessonPerWeeks}}
</div>
</div>

参考资料在这里:

angular2-ngmodel-inside-ngfor-data-not-binding-on-input

angular2-binding-of-name-attribute-in-input-elements-with-ngfor

dynamic-angular2-form-with-ngmodel-of-ngfor-elements

于 2017-03-20T06:42:16.370 回答