Angular 响应式表单的 formArrays 未按预期进行排序

Angular Reactive form's formArrays not binding as intended on sort

反应式表单控件无法排序。从 Google 收到的地方自动完成保存在一个数组中,然后我改变了它在数组中的顺序。当我控制台日志时,我看到数组已经改变了顺序,但它没有绑定到 UI。 在 stackblitz 中添加了代码。

产生错误的步骤:

  1. 添加三个地址(自动完成)和密码

  2. 然后点击排序地址按钮。现在,每次单击排序地址按钮时,您都会看到 pincode 发生变化,但不会看到地址

这是 stackblitz 上的代码:

ngOnInit() {
    this.myForm = this._fb.group({
        name: ['', [Validators.required, Validators.minLength(5)]],
        addresses: this._fb.array([
            this.initAddress(),
        ])
    });
}

sortAddress() {
    const B = [2, 1, 0];
    this.myForm.get('addresses').setValue(B.map((entry) => 
        this.myForm.get('addresses').value[entry]));
}

initAddress() {
    return this._fb.group({
        street: ['', Validators.required],
        postcode: ['']
    });
}

addAddress() {
    const control = <FormArray>this.myForm.controls['addresses'];
    control.push(this.initAddress());
}

尝试为您的 writeValue() 函数添加值修改:

public writeValue(value: any) {
  if (!value || value === null) {
    this.resetLocation();
    // this.updatePhotoComponent(value);
  }
  // this line actually writes changed value into its input box
  else {
    this.renderer.setProperty(this.location.nativeElement, 'value', value.address);
  }
}

已更新 STACKBLITZ:https://stackblitz.com/edit/angular-reactive-forms-eqve8a?file=app/google-place.component.ts