【问题标题】:Angular FormControl CheckBox selection marks every siblingAngular FormControl CheckBox 选择标记每个兄弟
【发布时间】:2020-08-05 17:34:28
【问题描述】:

StackBlitz:http://stackblitz.com/edit/angular-jul7bv

我在使用 Angular FromControl 时遇到问题,它是基于 od 传递的数据动态创建的。

我的列表显示特定数据的组和子组,一切工作几乎完美无缺,但每当我检查子组时,它的每个兄弟都被标记,我无法找出问题所在。

这是我的html:

<div *ngFor="let chapter of checkboxControlLabels; let i = index;">
      <div class="input-checkbox-subgroup-list__checkbox">
        <div class="input-checkbox">
          <input type="checkbox" [attr.id]="chapter.id + '_checkboxControl_' + i"
            [formControl]="getChapterControl(i)" />
          <label [attr.for]="chapter.id + '_checkboxControl_'+ i">{{ chapter.title }} </label>
        </div>
      </div>
      <div class="input-checkbox-subgroup-list__checkbox" *ngFor="let chart of chapter.charts; let x = index;">
        <div class="input-checkbox chart">
          <input type="checkbox" [attr.id]="chart.title + '_checkboxControl_' + x" [formControl]="getChartControl(i, x)" />
          <label [attr.for]="chart.title + '_checkboxControl_' + x">{{ chart.heading }} </label>
        </div>
      </div>
    </div>

这就是我映射特定 FormControl 的方式:

  getChartControl(chapterIndex: string, chartIndex: number) {
    return this.data.controls[chapterIndex].get('charts').controls[chartIndex];
  }

当我检查子组时,如下图所示,有 11 个被选中,我不知道这怎么可能。

更有趣的是,这不适用于组...所以如果我检查第一个组,则只会选择一个...

这是我稍后使用的 FormGroupModel:

this.chapterChartsData.forEach(chapters => {
      dataForm.push(new FormGroup({
        chapter: new FormControl(false),
        charts: new FormArray(Array(chapters.charts.length).fill(new FormControl(false)))
      }))
    });

【问题讨论】:

  • 你能创建stackbliz吗?
  • 也分享了formgroup/formarray的初始化如this.data。
  • stackblitz 很难创建,因为我为此使用了很多组件。我正在使用的初始 FormGroup 已添加。
  • @Krzysztof 将此视频发送至youtu.be/acDFvTPMKxM
  • stackblitz.com/edit/angular-jul7bv 我已经创建并重复了我遇到的问题,请看一下。谢谢!

标签: javascript angular forms checkbox form-control


【解决方案1】:

显然问题在于填充这样的表单控件列表:

charts: new FormArray(Array(chapters.charts.length).fill(new FormControl(false)))

【讨论】:

    猜你喜欢
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2022-01-22
    • 1970-01-01
    • 2011-09-28
    • 2011-12-13
    相关资源
    最近更新 更多