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

相关内容

热门资讯

第6分钟神器!微乐小程序黑科技... 第6分钟神器!微乐小程序黑科技,微乐家乡破解版(开挂)一直真的有挂(2026)进入游戏-大厅左侧-新...
透视好友!微乐小程序免费黑科技... 透视好友!微乐小程序免费黑科技,微乐陕西小程序辅助(透视)都是是有挂(哔哩哔哩)1、透视好友!微乐小...
第9分钟下载!微乐小程序免费黑... 第9分钟下载!微乐小程序免费黑科技,微乐小程序微乐房间怎么开挂(开挂)都是有挂(2026)1、微乐小...
备受关注的!微乐小程序黑科技,... 备受关注的!微乐小程序黑科技,微乐小程序辅助教程(透视)真是是真的挂(哔哩哔哩)微乐小程序辅助教程是...
5分钟神器!微乐小程序黑科技,... 5分钟神器!微乐小程序黑科技,微乐春天扑克开挂辅助插件(开挂)果然存在有挂(2026)5分钟神器!微...
透视辅助!微乐小程序免费黑科技... 透视辅助!微乐小程序免费黑科技,微乐贵阳麻将辅助(透视)竟然真的有挂(哔哩哔哩)1、玩家可以在微乐小...
第1分钟教程!微乐小程序黑科技... 第1分钟教程!微乐小程序黑科技,微乐自建房免费黑科技下载苹果(开挂)切实是真的挂(2026)1)微乐...
经调查!微乐小程序黑科技,微乐... 经调查!微乐小程序黑科技,微乐小程序免费黑科技(透视)一贯真的是有挂(哔哩哔哩)1)微乐小程序免费黑...
4分钟脚本!微乐小程序免费黑科... 4分钟脚本!微乐小程序免费黑科技,微信小程序怎么开挂(开挂)本来真的是有挂(2026)微乐小程序免费...
网友热议!微乐小程序黑科技,微... 网友热议!微乐小程序黑科技,微乐自建房辅助软件(透视)切实真的是有挂(哔哩哔哩)1、游戏颠覆性的策略...