Home > database >  Angular: Custom form components do not react to value change - like 2 way data binding
Angular: Custom form components do not react to value change - like 2 way data binding

Time:10-07

So I am creating my own form component that has a similar issue to the one here in this article

https://coryrylan.com/blog/angular-custom-form-controls-with-reactive-forms-and-ngmodel

I forked the code there to illustrate the point ... https://stackblitz.com/edit/angular-8afwjx?file=src/app/app.component.html

You can see that where ngModel is used, the other element that uses the same one gets updated all the time....becuase of 2 way data binding

but down in the reactive form, when I am trying to use the formControlName, when I toggle the control (either of them) the form gets udpated, but the other control not.

How do I make my custom control to react to value changes correctly? do I need to subscribe to it? I find it odd

CodePudding user response:

You can bind singe formControl instance to multiple input using formControl directive.To keep the controls in sync we can set the value property of the form control.

<form [formGroup]="myForm" (ngSubmit)="submit()">
  <label for="switch-2">Reactive Forms</label>
  <app-switch id="switch-2" [value]="switchControl.value" [formControl]="switchControl"></app-switch>

  <label for="switch-2">Reactive Forms2</label>
  <app-switch id="switch-2" [value]="switchControl.value" [formControl]="switchControl"></app-switch>

  <hr />
  <button>Submit</button>

  <br />
  <h2>Form value</h2>
  {{ myForm.value | json }}
</form>

Live Working Example

You can check more information here in Corylan Article

CodePudding user response:

Personally I don't like use [value] and formControl in the same tag. So, another approach is use ngModel for one of the "inputs"

  <app-switch id="switch-2" 
         [ngModel]="myForm.value.mySwitch" 
         (ngModelChange)="myForm.get('mySwitch').setValue($event)"
         [ngModelOptions]="{standalone:true}">
  </app-switch>

NOTE: the situation the same FormControl in two inputs differents happens always -it's not only in your custom form Control-

  • Related