Angular的patchValue()方法不会更新Ant Design自定义表单控件。
创始人
2024-10-24 08:31:50
0

在使用Angular的patchValue()方法更新Ant Design自定义表单控件时,可能会遇到无法更新的问题。这是因为Ant Design自定义表单控件可能需要使用setValue()方法来更新值,而不是使用patchValue()方法。

以下是一个解决方法的示例代码:

在自定义表单控件的组件中,实现ControlValueAccessor接口,并在writeValue()方法中使用setValue()方法更新值:

import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'custom-control',
  template: `
    
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomControlComponent),
      multi: true
    }
  ]
})
export class CustomControlComponent implements ControlValueAccessor {
  value: any;
  onChange: any = () => {};
  onTouched: any = () => {};

  writeValue(value: any) {
    this.value = value;
  }

  registerOnChange(fn: any) {
    this.onChange = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouched = fn;
  }

  updateValue(value: any) {
    this.value = value;
    this.onChange(value);
    this.onTouched();
  }
}

然后,在父组件中,使用ViewChild来获取自定义表单控件的实例,并调用updateValue()方法来更新值:

import { Component, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { CustomControlComponent } from './custom-control.component';

@Component({
  selector: 'app-root',
  template: `
    
` }) export class AppComponent { @ViewChild('customControl') customControl: CustomControlComponent; form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ customValue: [''] }); } updateValue() { const value = 'new value'; this.customControl.updateValue(value); this.form.patchValue({ customValue: value }); } }

在父组件中,我们使用ViewChild来获取自定义表单控件的实例,并在updateValue()方法中调用updateValue()方法来更新值。然后,我们使用patchValue()方法来更新表单控件的值。这样,无论是在自定义表单控件中还是在表单中,都能正确地更新值。

相关内容

热门资讯

记者发布!wepoker私人局... 记者发布!wepoker私人局透视方法(辅助挂)真是有挂(讲解有挂)1、金币登录送、破产送、升级送、...
教程辅助!hhpoker德州有... 教程辅助!hhpoker德州有挂吗(辅助挂)其实是有挂(有挂方法)1、这是跨平台的hhpoker德州...
六分钟了解!德普之星辅助软件(... 六分钟了解!德普之星辅助软件(辅助挂)真是是有挂(有挂透视)1、进入游戏-大厅左侧-新手福利-激活码...
详细说明!aapoker辅助工... 详细说明!aapoker辅助工具安全吗(辅助挂)一贯真的有挂(有挂猫腻)aapoker辅助工具安全吗...
总算了解!aapoker插件(... 总算了解!aapoker插件(辅助挂)本来是真的有挂(有挂秘诀)1、下载好aapoker插件正确养号...
重磅来袭!pokermaste... 重磅来袭!pokermaster修改器(辅助挂)真是存在有挂(有挂讲解)1、pokermaster修...
六分钟了解!拱趴大菠萝万能挂图... 六分钟了解!拱趴大菠萝万能挂图解(辅助挂)竟然存在有挂(揭秘有挂)暗藏猫腻,小编详细说明拱趴大菠萝万...
总算明白!wpk私人辅助(辅助... 总算明白!wpk私人辅助(辅助挂)一直是真的有挂(有挂辅助)1、下载好wpk私人辅助正确养号方法之后...
玩家必看科普!aapoker真... 玩家必看科普!aapoker真的假的(辅助挂)切实真的是有挂(有挂技巧)1、完成aapoker真的假...
一分钟了解!德普之星辅助器(辅... 一分钟了解!德普之星辅助器(辅助挂)竟然真的是有挂(确实有挂)1.德普之星辅助器 选牌创建新账号,点...