3
votes

i was trying to declare a component as Form Control.

<my-child-component formControlName="selectedSeats"></my-child-component>

Based on this answer i tried something like this using ControlValueAccessor,

public propagateChange: any = () => {};
public validateFn: any = () => {};

get selectedClasses() {

    return this.myForm.get('selectedSeats').value;
}
set selectedClasses(val) {
    this.propagateChange(val);
}
public ngOnChanges(inputs) {

}
public writeValue(value) {

}
public registerOnChange(fn) {
    this.propagateChange = fn;
}
public registerOnTouched(fn) {
}

public validate(c: FormControl) {
    return this.validateFn(c);
}

I am trying to pass the value of this.myForm.get('selectedSeats').value as component value and trying to bind to formcontrolname. But this code not working neither not throwing error.

could someone please tell me how to set this.myForm.get('selectedSeats').value value as my-child-component value and pass to formcontrol ?

parent component is Dynamic reactive nested form. inside the parent form i am calling another child-component which has its own set of form and it will return one value and it will be stored on selectedSeats input field. So now i need to pass that field value to parent and bind on parent nested form using formcontrol.

1
Just a question : why would you do that ?user4676340
parent component is Dynamic reactive nested form. inside the parent form i am calling another child-component which has its own set of form and it will return one value and it will be stored on input field. So now i need to get that field value and bind on parent nested form as formcontrol.Munna Babu
Well I think you should create reactive forms based on your model, not on your components, this would be easier for you.user4676340
You have to provide the Value Accessor in the component meta data like so: provide: [{NG_VALUE_ACCESSOR,useExisting: forwardRef(() => CustomInputComponent), multi: true}]Shadowlauch
yes already those were done :(Munna Babu

1 Answers

0
votes

You should take formControl object instead of formControlName. Create a input in your component and take object. Your code will look like this:

export class MyChildComponent {
  @Input() formControlObject: FormControl;

  getControlValue(){
    return this.formControlObject.value;
  }
}

Now you will pass object to this component like this:

<my-child-component [formControlObject]="myForm.controls['selectedSeats']"></my-child-component>

Hope it will help