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()方法来更新表单控件的值。这样,无论是在自定义表单控件中还是在表单中,都能正确地更新值。

相关内容

热门资讯

实测分享!吉祥填大坑小程序辅助... 实测分享!吉祥填大坑小程序辅助,超级三加一辅助软件,详细挂(有挂实锤)小薇(辅助器软件下载)致您一封...
免费测试版!老友跑得快辅助小说... 免费测试版!老友跑得快辅助小说最新章节,广西老友玩有破解码,详细教程(有挂教学)运老友跑得快辅助小说...
专业讨论!边锋老友杰克辅助,甘... 专业讨论!边锋老友杰克辅助,甘肃胡乐白银辅助,详细插件(有挂方略)甘肃胡乐白银辅助是不是有人用挂微扑...
科技揭秘!hhpoker作笔实... 科技揭秘!hhpoker作笔实战视频,赣牌圈破解器,详细工具(真实有挂)1、完成hhpoker作笔实...
避坑细节!四川长牌皮皮游戏挂,... 避坑细节!四川长牌皮皮游戏挂,微信雀神挂件开挂辅助,详细插件(有挂细节)微信雀神挂件开挂辅助脚本下载...
玩家亲测!博乐填大坑有没有bu... 玩家亲测!博乐填大坑有没有buff,微友辅助神器下载,详细攻略(有挂解惑)1、起透看视 博乐填大坑有...
必备教程!微乐小程序卡五星脚本... 必备教程!微乐小程序卡五星脚本,新超圣辅助靠谱不,详细脚本(新版有挂)1、全新机制【微乐小程序卡五星...
一起来讨论!哥哥打大a辅助神器... 一起来讨论!哥哥打大a辅助神器,钱柜手游辅助,详细技巧(果真有挂)1、哥哥打大a辅助神器免费脚本咨询...
每日必看推荐!青鸟辅助器,hh... 每日必看推荐!青鸟辅助器,hh poker有没有辅助软件,详细器(有挂辅助)1、hh poker有没...
实操分享!胡乐胡乐辅助脚本可靠... 实操分享!胡乐胡乐辅助脚本可靠吗,wepokerplus辅助作弊,详细app(有挂猫腻)1、让任何用...