我想列出您可以查询的月份。
我面临的问题是我无法真正选中一个复选框。
在另一个变体中,我尝试在后面的代码中设置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;
  }

最佳答案

我在每个循环上添加了[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>

关于javascript - 无法选中第二个循环内的复选框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51745091/

10-09 17:41