Angular Reactive Form Array 仅显示数组中的 1 个项目

Angular Reactive Form Array is only displaying 1 item from the array

我正在 Angular 12 中构建一个响应式表单 (edit/new),其中包含一个名为 'actions' 的表单数组。 我有表单可以提交新的和更新数组中现有的多个项目。 我遇到的问题是当编辑表单在浏览器中加载时,只显示第一个数组项。 肯定正在检索数组中的多个项目,只是不显示。这是代码:

component.ts 文件

export class AdviceEditComponent implements OnInit {
id: number;
isAddMode: boolean;
adviceForm: FormGroup;
validationErrors: string[] = [];
actions: FormArray;

constructor(private route: ActivatedRoute,
            private adviceService: AdviceService,
            private router: Router, private fb: FormBuilder) {              
}

ngOnInit() {
  this.id = this.route.snapshot.params['id'];
      this.isAddMode = !this.id;

      this.adviceForm = this.fb.group({
        title: ['', Validators.required],
        description: ['', Validators.required],
        sourceUrl: ['', Validators.required],
        actions: this.fb.array([this.createAction()]) 
    });

    if (!this.isAddMode) {
        this.adviceService.getAdvice(this.id)
            .pipe(first())
            .subscribe(x => this.adviceForm.patchValue(x));
    }
}

createAction(): FormGroup {
  return this.fb.group({
    id: '0',
    what: '',
    how: ''
  });
}

get controls() { // a getter!
  return (<FormArray>this.adviceForm.get('actions')).controls;
}

onAddAction(): void {
  this.actions = this.adviceForm.get('actions') as FormArray;
  this.actions.push(this.createAction());
}
}

component.html 文件

<div class="row">
  <div class="col-sm-12">
    <form [formGroup]="adviceForm" (ngSubmit)="onSubmit()">
      <div class="row">
        <div class="col-sm-10">
          <div class="form-group">
            <label for="title">Title</label>
            <input type="text" id="title" formControlName="title" class="form-control">
            <span *ngIf="!adviceForm.get('title').valid && adviceForm.get('title').touched" class="help-block">
              Please enter a Title
            </span>

          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-sm-10">
          <div class="form-group">
            <label for="description">Description</label>
            <textarea type="text" id="description" formControlName="description" class="form-control"
              rows="6"></textarea>
            <span *ngIf="!adviceForm.get('description').valid && adviceForm.get('description').touched"
              class="help-block">
              Please enter a Description
            </span>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-sm-10">
          <div class="form-group">
            <label for="sourceUrl">Source Url</label>
            <input type="text" id="sourceUrl" class="form-control" formControlName="sourceUrl">
            <span *ngIf="!adviceForm.get('sourceUrl').valid && adviceForm.get('sourceUrl').touched" class="help-block">
              Please enter a Source Url
            </span>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-xs-12" formArrayName="actions">
          <div class="row" *ngFor="let action of adviceForm.get('actions')['controls']; let i = index" [formGroupName]="i"
            style="margin-top: 10px; margin-left: 15px;">

            <div class="col-xs-8 mr-2">
              <input type="text" class="form-control" formControlName="what">
            </div>

            <div class="col-xs-2 mr-2">
              <input type="text" class="form-control" formControlName="how">
            </div>
            <div class="col-xs-2">
              <button class="btn btn-danger">X</button>
            </div>
          </div>
          <hr class="ml-3">
          <div class="row">
            <div class="col-xs-12 ml-5">
              <button type="button" class="btn btn-success" (click)="onAddAction()">Add Action</button>
            </div>
          </div>

        </div>
      </div>
      <div class="row">
        <div class="col-sm-12 mt-3 ml-3">
          <button type="submit" class="btn btn-success mr-2" [disabled]="!adviceForm.valid">Save</button>
          <button type="button" class="btn btn-danger" (click)="onCancel()">Cancel</button>
        </div>
      </div>
    </form>
  </div>
</div>

几个小时以来我一直在努力解决这个问题,但我就是看不出我做错了什么。任何帮助将不胜感激。谢谢。

.patchValue() 将更新现有的 FormArray。它不会从数组中创建或删除项目。 这里您在 actions formArray 中只有一项。

请尝试以下代码。

        this.adviceService.getAdvice(this.id)
            .pipe(first())
            .subscribe(x => {
                const actions = this.adviceForm.get('actions') as FormArray;
                actions.clear();
                x.actions.map(action => actions.push(this.createAction()))
                this.adviceForm.patchValue(x)
             });