xavier
xavier

Reputation: 2049

Angular 7. Don't check a validation in a reactive form the first time

In Angular 7, I have the following code:

    this.formGroup = this.formBuilder.group({
      id: [],
      name: ['', [Validators.required], this.validateSomething.bind(this)],
    });

then I do some things and finally I initialize the values with an object myObject that I obtain from my DB and I know it does not break any validation:

    this.formGroup.setValue({
      id: myObject.id,
      name: myObject.name
    }, {
      emitEvent: false
    });

My validateSomething is quite complex and I would like that, in my initial setValue it didn't run to save some computations.

I found the function setValidators() and I thought I could do something like:

    this.formGroup = this.formBuilder.group({
      id: [],
      name: ['', [Validators.required]],
    });
    this.formGroup.setValue({
      id: myObject.id,
      name: myObject.name
    }, {
      emitEvent: false
    });
this.formGroup.controls.name.setValidator(validateSomething.bind(this));

But it doesn't work. The validation simply does not work anymore.

Any idea? Thanks!

Upvotes: 2

Views: 2589

Answers (1)

riorudo
riorudo

Reputation: 1227

In your validation method validateSomething you could check if the field is touched and / or dirty before validate.

Something like:

this.myForm.get('name').touched && this.myForm.get('name').dirty.

Upvotes: 2

Related Questions