无法选中第二个循环内的复选框

时间:2018-08-08 11:04:37

标签: javascript angular typescript ngfor

我想列出一些年份,您可以查询一下。
我面临的问题是我无法真正选中一个复选框。
在另一个变体中,我尝试在后面的代码中设置checked,但UI保持未选中状态。

我的猜测是,这与彼此内部的2个循环有关,但我不是如何解决这个问题。

模型

export class YearsAndMonths {
  public year: number;
  public months: Month[] = [
    { name: "January", numeric: 1, checked: false },
...
  ]
}

export class Month {
  public name: string;
  public checked: boolean;
}

HTML

<form *ngIf="years">
  <section *ngFor="let year of years; let y = index">
    <div class="row">
      <strong>{{year.year}}</strong>
    </div>

    <mat-checkbox name='ym{{y}}{{i}}' *ngFor="let month of year.months; let i = index; trackBy: trackByIdx">
      {{month.name}}
    </mat-checkbox>
  </section>
</form>

HTML 变体

<mat-checkbox *ngFor="let month of year.months; let i = index; trackBy: trackByIdx"
              class="row" name='ym{{y}}{{i}}' [checked]="month.checked" (change)="onMonthChanged(month)">
  {{month.name}}    
</mat-checkbox>

组件

  @Input() years: YearsAndMonths[];
  trackByIdx(index: number, obj: any): any {
    return index;
  }

1 个答案:

答案 0 :(得分:0)

我在每个循环中添加了[trackByIdx][1](在我的情况下是几年)...使其工作。

<form *ngIf="years">
  <section *ngFor="let year of years; let y = indexOfYears; trackBy: trackByIdx">
    <div class="row">
      <strong>{{year.year}}</strong>
    </div>
    <!--<div *ngFor="let month of year.months; let i = index; trackBy: trackByIdx" class="form-check row">
      <input type="checkbox" class="form-check-input" [checked]="month.checked" (change)="onMonthChanged(month)" name='ym{{y}}{{i}}'>
      <label class="form-check-label">{{month.name}}</label>
    </div>-->

    <mat-checkbox *ngFor="let month of year.months; let i = indexOfMonths; trackBy: trackByIdx"
                  class="row" name='ym{{y}}{{i}}' [checked]="month.checked" (change)="onMonthChanged(month)">
      {{month.name}}    
    </mat-checkbox>

  </section>
</form>