0

enter image description here

I have a nested form. Parent form has two controls: phoneInfo and remember.

Is there a way for child form to return only one value (fullPhone) instead of entire object?

Desired result:

{
    "phoneInfo": (returns fullPhone),
    "remember": true
}

I have tried using ControlValueAccessor

Current providers in child form:

  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => PhoneFormComponent),
      multi: true
    },
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PhoneFormComponent),
      multi: true
    }
  ]

Control value accessor interface:

  public onTouched: () => void = () => {};

  writeValue(val: any): void {
    console.log(val);
    val && this.form.setValue(val, { emitEvent: false });
  }
  registerOnChange(fn: any): void {
    this.form.valueChanges.subscribe(fn);
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  validate(c: AbstractControl): ValidationErrors | null {
    return this.form.valid ? null : { invalidForm: { valid: false, message: 'form fields are invalid' } };
  }
4

1 回答 1

2

I think you'll have to modify what's inside registerOnChange:

registerOnChange(fn: any): void {
  this.form.valueChanges.pipe(
    pluck('fullPhone'),
  ).subscribe(fn);
}
于 2020-07-25T13:06:36.947 回答