【问题标题】:Angular Reactive form's formArrays not binding as intended on sortAngular Reactive表单formArray未按排序预期绑定
【发布时间】:2018-07-09 10:24:11
【问题描述】:

无法对反应式表单控件进行排序。从 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());
}

【问题讨论】:

    标签: angular google-maps-api-3 google-places-api angular-reactive-forms


    【解决方案1】:

    尝试为您的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

    【讨论】:

    • 谢谢。为什么要通过 writevalue 设置属性?
    • &lt;app-google-place ...&gt; 是您编写的自定义表单元素,其模型通过formControlName 属性更新,由writeValue 函数监视,自定义元素负责更新其视图(它可以通过多种方式完成:使用ngModel、反应形式方法、本机元素更新等)。您使用本机元素方法来重置位置值,但您只介绍了空值的情况,我添加了元素更新以防非空值。
    猜你喜欢
    • 2020-12-19
    • 2020-07-24
    • 2019-01-31
    • 2018-12-22
    • 1970-01-01
    • 2018-12-22
    • 2020-03-31
    • 2016-02-27
    • 2021-05-30
    相关资源
    最近更新 更多