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

相关内容

热门资讯

透视智能ai!德普之星透视辅助... 透视智能ai!德普之星透视辅助软件,悦悦娱乐辅助,有挂教程(竟然是有辅助修改器)-哔哩哔哩悦悦娱乐辅...
记者获悉!aapoker真的假... 记者获悉!aapoker真的假的(透视)闲聚app辅助软件(真是真的有辅助辅助器)-哔哩哔哩1、任何...
透视黑科技!竞技联盟透视插件(... 透视黑科技!竞技联盟透视插件(透视)微乐南昌辅助神器(好像是有辅助辅助器)-哔哩哔哩1、微乐南昌辅助...
无独有偶!aapoker真的假... 无独有偶!aapoker真的假的(透视)椰岛常胜游戏辅助工具免费版(本来真的有辅助app)-哔哩哔哩...
反观!约局吧辅助器(透视)湖北... 反观!约局吧辅助器(透视)湖北卡五星插件(都是是有辅助平台)-哔哩哔哩1、让任何用户在无需湖北卡五星...
更值得关注的是!hhpoker... 更值得关注的是!hhpoker辅助软件是真的么(透视)潮汕掌手娱辅助器(果然是真的辅助神器)-哔哩哔...
现场直击!pokeplus脚本... 现场直击!pokeplus脚本(透视)微乐家乡官方app(竟然是有辅助app)-哔哩哔哩1、微乐家乡...
为了进一步!拱趴大菠萝有什么挂... 为了进一步!拱趴大菠萝有什么挂(透视)星悦云南丽江卡二辅助(一直是有辅助辅助器)-哔哩哔哩星悦云南丽...
昨日!德普之星的辅助工具介绍(... 昨日!德普之星的辅助工具介绍(透视)福建大玩家透视工具(好像是真的辅助修改器)-哔哩哔哩1.福建大玩...
现就发布提示!wejoker辅... 现就发布提示!wejoker辅助器要钱玩吗(透视)雀友会广东潮汕辅助脚本(其实有辅助下载)-哔哩哔哩...