Search code examples
angular2-forms

What is the right way to bind 2 angular 2 form controls together


I want to hook up 2 input controls to each other, so when one changes, it updates the other. As an example, its 2 percentage fields, if I set one to 80, the other will get set to 20 to balance it to total 100.

Both inputs are in a form group, so I feel like I should use these and methods on these to subscribe to value changes and not touch native elements or events.

Can anyone suggest the base way to go about it?


Solution

  • I'm using angular reactive forms and was able to create a component that binds to the form FormGroup and the names of the controls, like this:

    <app-percentage-balance
        [formGroup]="form"
        firstControlName="firstControl"
        secondControlName="firstControl">
    

    in my component I have:

    @Input() formGroup: FormGroup;
    @Input() firstControlName: string;
    @Input() secondControlName: string;
    
    public ngOnInit(): void {
        this.firstControl = this.formGroup.controls[this.firstControlName] as FormControl;
        this.secondControl = this.formGroup.controls[this.secondControlName] as FormControl;
    
        this.firstControl.statusChanges.subscribe((status) => {
          if (status == "VALID") {
            // do stuff
          }
        });
    
        this.secondControl.statusChanges.subscribe((status) => {
          if (status == "VALID") {
            // do stuff
          }
        });
    }