typescript 我如何访问这个嵌套数组,使它显示我的< input>字段?

mkshixfv  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(104)

我尝试显示这个输入字段“levels”。最后我希望有一个add按钮来创建多个级别。每个learningGoal应该在我创建learningGoal之前获得级别。所以json应该看起来像这样:

{
  "name": "name rubric",
  "learningGoals": [
    {
      "description": "learning goal description",
      "levels": [
        {
          "name": "level name",
          "criteras": []
        }
        {
          "name": "level name",
          "criteras": []
        }
      ]
    }
  ]

此时,“级别”为空

<form [formGroup]="rubricForm">
  <ng-template matStepLabel>Naam & Niveaus</ng-template>

  <mat-form-field>
    <input matInput placeholder="Naam" formControlName="name">
  </mat-form-field>

  <div formArrayName="learningGoals">
    <div *ngFor="let learningGoal of learningGoals().controls; let i = index" [formGroupName]="i">
      <div formArrayName="levels">
        <div *ngFor="let level of levels?.controls; let j = index" [formGroupName]="j">
          <mat-form-field>
            <input matInput placeholder="Naam" formControlName="name">
          </mat-form-field>
        </div>
      </div>
    </div>
  </div>

</form>

我的 typescript :

rubricForm: FormGroup
constructor(private fb: FormBuilder) {
  this.rubricForm = this.fb.group({
    name: ["", Validators.required],
    learningGoals: this.fb.array([
      this.initLearningGoal()
    ])
  });
}

initLevel() {
  return this.fb.group({
    name: "",
  });
}

initLearningGoal() {
  return this.fb.group({
    description: "",
    levels: this.fb.array([
      this.initLevel()
    ])
  });
}

rubric(): FormArray {
  return this.rubricForm.get("rubric") as FormArray;
}
learningGoals(): FormArray {
  return this.rubricForm.get("learningGoals") as FormArray;
}

get levels(): FormArray {
  return this.learningGoals()
    .get('levels') as FormArray;
}

我试过删除for循环,但它给了我错误:
错误错误:找不到路径为的控件:“学习目标-〉级别”。
所以我想我得把表格组夹在中间。
任何帮助都是感激的!

0g0grzrc

0g0grzrc1#

我已使用以下方法修复此问题:

levels(i: number): FormArray {
    const learningGoal = this.learningGoals.at(i) as FormGroup;
    return learningGoal.get('levels') as FormArray;
  }

并使用:

<div formArrayName="learningGoals">
    <div *ngFor="let learningGoal of learningGoals.controls; let i = index" [formGroupName]="i">
      <div formArrayName="levels">
        <div *ngFor="let level of levels(i).controls; let j = index" [formGroupName]="j">
          <mat-form-field>
            <input matInput placeholder="Naam" formControlName="name">
          </mat-form-field>
          <button mat-icon-button (click)="deleteLevel(i, j)">
            <mat-icon>delete</mat-icon>
          </button>
        </div>
        <button mat-icon-button (click)="addLevel(i)">
          <mat-icon>add</mat-icon>
        </button>
      </div>
    </div>
  </div>

相关问题