3

我正在尝试使用该ControlValueAccessor界面创建自定义 FormControl。我的目标是从父表单中的自定义 FormControl 中取回如下对象(示例):

{
  prop1: int,
  prop2: string,
  prop3: { prop31: int, prop32: string, prop33: int }
}

我的自定义表单控件(为简洁起见省略了装饰器):

export class MyCustomControlComponent implements OnInit, ControlValueAccessor {

    private _value: any
    form: FormGroup

    set value(value: any) {
        this._value = value
        this.notifyValueChange()
    }

    get value() { return this._value }

    onChange: (value) => {}
    onTouched: () => {}

    constructor(
        public fb: FormBuilder,
    ) {
        this.form = this.fb.group({
            prop1: [null, Validators.compose([Validators.required, Validators.min(0)])],
            prop2: [null, Validators.required],
            prop3: this.fb.group({
                prop31: [null, Validators.required],
                prop32: [null, Validators.required],
                prop33: [null, Validators.required],
            }),
        })
    }

    setValues() {
        const formValues = this.form.value
        this.writeValue(formValues)
    }

    notifyValueChange() {
        if (this.onChange) {
            this.onChange(this.value)
        }
    }

    ngOnInit(): void {
        this.form.valueChanges.subscribe(_ => this.setValues())
    }

    writeValue(obj: any): void { this.value = obj }
    registerOnChange(fn: any): void { this.onChange = fn }
    registerOnTouched(fn: any): void { this.onTouched = fn }
    setDisabledState(isDisabled: boolean): void { }
}

父表格:

childForm: FormControl
constructor(...) {
  childForm = new FormControl()
}
ngOnInit() {
  this.childForm.valueChanges.subscribe(value => console.log(value))
}

在父表单中,我从自定义表单控件中获取值。但是一旦我尝试从父表单设置一些初始值,它们都不会出现在自定义表单中。我的理解是,我需要在自定义控件的内部映射从父级接收到的对象,FormGroup但我不确定在哪里以及如何。帮助将不胜感激。此外,欢迎对此提出更好的方法(如果有)的意见。

编辑

回答我为什么要尝试实现这一点:我有一个非常大的表单,并且与上面给出的这个示例对象有关的一部分实际上是动态的——这意味着我需要在最后存储这些对象的数组。为了消除一些混乱,我试图将此部分移动到单个表单控件中,以便我可以使用 aFormArray来处理它。

4

0 回答 0