Search code examples
angularcontrolvalueaccessor

Can Angular value accessor return only one variable instead of object?


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' } };
  }

Solution

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

    registerOnChange(fn: any): void {
      this.form.valueChanges.pipe(
        pluck('fullPhone'),
      ).subscribe(fn);
    }