A
A
Adel Khalitov2019-02-22 21:47:46
Angular
Adel Khalitov, 2019-02-22 21:47:46

How to check FormControl for validity from a function in angular?

There is this group:

this.OfferControl = this.fb.group({
      leadLink: this.LeadControl.get('leadId').value,
      area: ['', Validators.required],
      regular: ['', Validators.required],
      time: '',
      details: this.fb.group({
        fot: ['', Validators.required],
        managerWage: ['', Validators.required],
        tinkoffCommission: ['', Validators.required],
        windowFond: ['', Validators.required],
        material: ['', Validators.required],
        profit: ['', Validators.required],
        itog: ['', Validators.required],
        itogMaterial: ['', Validators.required],
      })
    });

I need when clicking on a button that is stored outside of a form:
<form [formGroup]="OfferControl">
......
</form>

<button (click)="some()">Действия</button>

Run the some() function and validate this group, that is, if there is an error, then highlight in red where it is empty (As in my example).
if (this.OfferControl.valid) {
...
}

This option simply checks if everything is ok and performs further actions, but does not highlight empty fields.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-02-23
@Xuxicheta

valid and hasError are present not only for the whole group, but also for each field.
To highlight a field in red, you create a conditional class attribute based on valid for this field.
for example for area
[class.error]="!OfferControl.get('area').valid"
and then the element will get the error class when it becomes invalid.
And there the standard classes are hung up, open the form in devtools and see how it changes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question