angularangular-reactive-formsangular-formsangular-formbuilder

How to get focused form control name in angular reactive forms with the help of ReactiveForms


One way i tried is adding OnFocus event on the form control.

Is there any possibility to get it with the help of reactiveFoms itself.


Solution

  • Based on your comment I don't see the relevance of determining focus on a control to validate such that 5 input fields don't exceed the sum of 100. So I propose we could use a common validator that does the work for us (checking all inputs in the group).

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      name = 'Angular 5';
    
      myForm: FormGroup;
    
      constructor(private fb: FormBuilder) {
        this.myForm = fb.group(
          {
            field1: [null],
            field2: [null],
            field3: [null],
            field4: [null],
            field5: [null],
          },
          { validator: this.myValidator }
        );
      }
    
      myValidator(group: FormGroup) {
        let sum = 0;
        for (let a in group.controls) {
          sum += group.get([a]).value;
        }
        console.log(sum > 100);
        return sum > 100 ? { notValid: true } : null;
      }
    }
    

    Working example: https://stackblitz.com/edit/angular-qxxmke?file=app%2Fapp.component.ts