angularformsangular2-form-validation

form async validation when updateOn is blur, to subscribe statusChanges or valueChanges


I am using form async validation with updatOn: 'blur' in my Angular7 application. stackblitz

in this situation, I need to check if the name is unique(async validation).

this.myForm.get('name').statusChanges.subscribe(status => {
    if (status === 'VALID') {
        // to save the name to database.
    } else {
        // to show some errors.
    }
});

question is, where to put this code?

Current way

I tried this,in child component

@Input()
set myForm(myForm: FormGroup) {
  this._myForm = myForm;
  this.myForm.get('name').statusChanges.subscribe(status => {    // to subscribe statusChanges here.
    if (status === 'VALID') {
        // to save the name to database.
    } else {
        // to show some errors.
    }
  });
}

get myForm() {
  return this._myForm;
}


_myForm: FormGroup

it worked. But I have at least 10 attributs to do form validation, this will add too many codes to this @Input() set myForm() {}, so I need to do this in another function.

So, I quit to subscribe statusChange in the @Input attribute. if not here, where should I do this?

And I can't subscribe statusChange in ngOnInit, cause value is undefined in ngOnInit.

Anyone helps me pls.


Solution

  • I think you can use directive in this case - Create a directive and add in the necessary input fields

    Directive

    @Directive({
      selector: '[dynamicValidation]'
    })
    export class DynamicValidationDirective {
    
      constructor(private control: NgControl) { }
    
      ngOnInit() {
        if (this.control && this.control!= undefined) {
          this.control.statusChanges.subscribe((status) => {
            // Your logic will go here
          });
        }       
      }
    }
    

    Now just add the directive in the specific input field

    Input

    <input [formControlName]="controlName"
                             type="text"
                             dynamicValidation        //Added the directive
                             class="form-control form-control-sm" />
    

    Now all the input fields will be tagged with a subscription and when the status changes the specific input value will get updated respectively

    Hope this helps you - Thanks !!