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

相关内容

热门资讯

黑科技脚本!wpk有外挂么,w... 黑科技脚本!wpk有外挂么,wepower辅助器,wpk教程(有挂总结)-哔哩哔哩(1)黑科技脚本!...
黑科技计算!aapoker德州... 黑科技计算!aapoker德州线上扑克辅助工具(黑科技ai)素来有挂(有挂安装)-哔哩哔哩;1分钟了...
黑科技教程!wpk俱乐部怎么盈... 黑科技教程!wpk俱乐部怎么盈利(智能ai)太坑了是有挂(大神讲解黑科技插件)-哔哩哔哩1、首先打开...
黑科技神器!德州AI智能辅助机... 黑科技神器!德州AI智能辅助机器人,智星德州菠萝,AI教程(有挂教程)-哔哩哔哩1、构建自己的微扑克...
黑科技有挂!来玩app德州安卓... 黑科技有挂!来玩app德州安卓有用吗(透明挂)总是真的有挂(有挂线上)-哔哩哔哩这是由厦门游乐互动科...
黑科技新版!线上wpk德州ai... 黑科技新版!线上wpk德州ai机器人(ai代打)太坑了真的有挂(黑科技教程黑科技教程)-哔哩哔哩1、...
黑科技ai!aapoker透视... 黑科技ai!aapoker透视辅助,wepoke有辅助挂,攻略方法(有挂详情)-哔哩哔哩是一款可以让...
黑科技透明挂挂!德州ai辅助工... 黑科技透明挂挂!德州ai辅助工具购买(透明挂)原本真的有挂(有挂下载)-哔哩哔哩;人气非常高,ai更...
黑科技讲解!wopoker辅助... 黑科技讲解!wopoker辅助真的假的(黑科技ai)太坑了真的有挂(AA德州教程黑科技插件)-哔哩哔...
黑科技辅助!aapoker外挂... 黑科技辅助!aapoker外挂,德扑之星系统发牌机制,教你教程(有挂规律)-哔哩哔哩1、德扑之星系统...