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插件功能辅助器(真是真的是有挂)是一款可以让一...
实测揭晓!创思维怎么开挂(辅助... 实测揭晓!创思维怎么开挂(辅助挂)aapoker如何设置胜率(原本真的有挂);1、超多福利:超高返利...
重大科普!情怀手机麻将辅助器(... 重大科普!情怀手机麻将辅助器(辅助挂)wepoker作弊辅助(原先存在有挂);1、让任何用户在无需A...
科普分享!蜜瓜大厅可以装挂吗(... 科普分享!蜜瓜大厅可以装挂吗(辅助挂)hhpoker辅助挂是真的吗(总是有挂);蜜瓜大厅可以装挂吗最...
科普常识!上饶打炸漏洞(辅助挂... 科普常识!上饶打炸漏洞(辅助挂)aapoker辅助怎么用(最初真的是有挂);上饶打炸漏洞软件透明挂更...
实测揭晓!边锋老友威海荣成辅助... 实测揭晓!边锋老友威海荣成辅助(辅助挂)wepoker私人局透视插件(原先是真的有挂);边锋老友威海...
实测发现!小闲川南手游辅助器(... 实测发现!小闲川南手游辅助器(辅助挂)hhpoker哪个俱乐部靠谱(切实真的是有挂)是一款可以让一直...
揭秘!陕西扣点点脚本辅助器(辅... 揭秘!陕西扣点点脚本辅助器(辅助挂)wepoker私人局辅助挂(固有是有挂),陕西扣点点脚本辅助器是...
记者爆料!赣牌圈的好牌几率(辅... 【福星临门,好运相随】;记者爆料!赣牌圈的好牌几率(辅助挂)wepoker买脚本靠谱吗(先前是有挂)...
我来教大家!手机透视辅助器ap... 我来教大家!手机透视辅助器app(辅助挂)wpk插件辅助(真是有挂);一、手机透视辅助器appAI软...