Alex JS
Alex JS

Reputation: 19

Get value from component inside validator

Needs to validate value from reactive form component inside child component, as value for validation I need value that`s only exist on child component.

The problem that I couldn`t pass value from component to validator

const PHONE_CONTROL_VALIDATOR = {
  provide: NG_VALIDATORS,
  useValue: phoneInputValidator,
  multi: true,
};

Any option to pass value from this into phoneInputValidator

Upvotes: 0

Views: 139

Answers (1)

Oleksii Pavlenko
Oleksii Pavlenko

Reputation: 1333

You have next option. First of all delete PHONE_CONTROL_VALIDATOR from yours componet. Next add to constructor

constructor(@Optional() @Self() public ngControl: NgControl) {
    // prevent error on initialization
    if (this.ngControl) {
      this.ngControl.valueAccessor = this;
    }
  }

public ngOnInit(): void {
    this.ngControl.control.setValidators([this.phoneInputValidator.bind(this)]);
    this.ngControl.control.updateValueAndValidity();
  }

public phoneInputValidator(control: AbstractControl): ValidationErrors {
// here you have this

Upvotes: 1

Related Questions