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

相关内容

热门资讯

重大通报!雀友会广东潮汕麻雀万... 重大通报!雀友会广东潮汕麻雀万能辅助器!总是存在有辅助app(有挂技术)1、点击下载安装,雀友会广东...
盘点几款!微乐江苏自建房辅助a... 盘点几款!微乐江苏自建房辅助app!好像真的有辅助app(有挂存在)1、在微乐江苏自建房辅助app插...
一分钟教会你!上品斗地主游戏辅... 一分钟教会你!上品斗地主游戏辅助!真是确实有辅助软件(有挂头条)1、上品斗地主游戏辅助免费辅助多个强...
一分钟揭秘!点点长牌源码!真是... 一分钟揭秘!点点长牌源码!真是存在有辅助挂(有挂教程)1、点点长牌源码免费脚本咨询教程、点点长牌源码...
这一现象值得深思!广东闲来辅助... 这一现象值得深思!广东闲来辅助免费!原来存在有辅助软件(有挂实锤)进入游戏-大厅左侧-新手福利-激活...
玩家必看分享!万能脚本辅助器!... 玩家必看分享!万能脚本辅助器!确实确实有辅助挂(有挂秘笈)万能脚本辅助器破解侠是真的助透视。每个模型...
2024教程!随意玩房卡辅助!... 2024教程!随意玩房卡辅助!原来真的有辅助技巧(发现有挂)1、让任何用户在无需随意玩房卡辅助安装教...
技术分享!大头大菠萝辅助!都是... 技术分享!大头大菠萝辅助!都是是真的有辅助技巧(有挂总结)1、起透看视 大头大菠萝辅助辅助软件价格2...
围绕透视问题!菠萝辅助破解版!... 围绕透视问题!菠萝辅助破解版!一贯真的是有辅助攻略(有挂分享)围绕透视问题!菠萝辅助破解版!一贯真的...
玩家必看攻略!胡乐辅助脚本!确... 玩家必看攻略!胡乐辅助脚本!确实真的有辅助软件(有挂分析)1、实时胡乐辅助脚本透视辅助更新:用户可以...