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、让任何用户在无需拱...
外挂指南!德普之星有辅助软件吗... 外挂指南!德普之星有辅助软件吗,xpoker辅助-原来一直总是有辅助app(哔哩哔哩)1、下载好xp...
外挂举措!werplan透视挂... 外挂举措!werplan透视挂,佛手大菠萝有挂吗-果然是真的有辅助软件(哔哩哔哩)1、佛手大菠萝有挂...
外挂妙计!德扑圈透视挂,拱趴大... 您好,拱趴大菠萝机器人这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩...
外挂技法!红龙poker作必弊... 外挂技法!红龙poker作必弊指令,sohoo开挂辅助-确实是真的有辅助教程(哔哩哔哩)1、玩家可以...
外挂方式!werplan外卦神... 外挂方式!werplan外卦神器,德州私人局脚本-其实一直总是有辅助神器(哔哩哔哩)德州私人局脚本脚...
外挂指南书!poker mas... 外挂指南书!poker master辅助,哈糖大菠萝开挂-其实真的是有辅助脚本(哔哩哔哩)1、首先打...
外挂步骤!德州局脚本,德普之星... 外挂步骤!德州局脚本,德普之星辅助工具如何设置-其实一直总是有辅助教程(哔哩哔哩)1、点击下载安装,...
外挂教程书!扑克之星辅助,大菠... 外挂教程书!扑克之星辅助,大菠萝免费辅助器-总是一直总是有辅助软件(哔哩哔哩)大菠萝免费辅助器破解侠...
外挂策略!aa poker辅助... 外挂策略!aa poker辅助包,德普之星透视辅助插件-一直真的是有辅助插件(哔哩哔哩)1、每一步都...