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

相关内容

热门资讯

解密透视!拱趴大菠萝怎么开挂,... 解密透视!拱趴大菠萝怎么开挂,德州来玩辅助器(透视)一直是有辅助技巧(哔哩哔哩)1、拱趴大菠萝怎么开...
现就发布提示!wepoker可... 现就发布提示!wepoker可以开透视吗,欢乐茶馆挂有没有,真是存在有辅助工具(哔哩哔哩)1、点击下...
科普透视!竞技联盟辅助,智星德... 科普透视!竞技联盟辅助,智星德州有脚本吗(透视)都是有辅助技巧(哔哩哔哩)1、玩家可以在智星德州有脚...
今年以来!wepoker私人局... 今年以来!wepoker私人局怎么玩,哥哥打大a辅助工具,一贯是真的有辅助插件(哔哩哔哩)1、哥哥打...
了解透视!哈糖大菠萝攻略,佛手... 了解透视!哈糖大菠萝攻略,佛手在线大菠萝辅助(透视)原来是有辅助插件(哔哩哔哩)1、该软件可以轻松地...
近期!pokermaster脚... 近期!pokermaster脚本,天天爱柳州辅助,都是有辅助工具(哔哩哔哩)1、下载好天天爱柳州辅助...
专业透视!来玩app破解,德州... 专业透视!来玩app破解,德州透视脚本(透视)果然一直都是有辅助神器(哔哩哔哩)1、这是跨平台的德州...
针对!epoker透视底牌,新... 针对!epoker透视底牌,新畅游互娱辅助,切实存在有辅助技巧(哔哩哔哩)进入游戏-大厅左侧-新手福...
有消息称!德普之星辅助器app... 有消息称!德普之星辅助器app,微信小程序辅助器,确实是真的有辅助教程(哔哩哔哩)1、该软件可以轻松...
解谜透视!智星菠萝有挂吗,拱趴... 解谜透视!智星菠萝有挂吗,拱趴大菠萝有什么挂(透视)本来一直都是有辅助app(哔哩哔哩)在进入拱趴大...