How do I receive the default value of a form control in my custom control (ControlValueAccessor)

Viewed 1299

Let's say I have a form like this:

this.form = fb.group({
        genders: [['MALE']],
    });

And I've implemented my own custom form control which implements the ControlValueAccessor interface. I understand that we have the writeValue method, but this method is only called when using either setValue or patchValue. How do I get the default value which was set in the FormBuilder's group method?

4 Answers

You can do this by passing a simple @Input() inside a component.

@Component({ selector: 'my-component', template: `....` })
export class Component extends ControlValueAccessor {
  @Input('property') property: any;
}

and then inside the HTML,

<my-component formControl="gender" [property]="value">

you want to receive the default from group value , try in your component :

this.form.value.genders

Or in your .html file you can use : {{ form.value. genders }}

Actually I just tried and writeValue is called twice but the second time it has the right value put as init value in the form object.

Related