How to raise mat-error in angular for just some specific field?

105 views Asked by At

I have a form where are sub categories and save button calls mat-error correctly for all the fields in all categories in once correctly if nothing entered. But I also have add button for each category and want to validate if just that fields have value before adding new fields?

1

There are 1 answers

0
Eliseo On

I imagine you has a FormArray. So you should use a getter

get myFormArray()
{
   return this.form.get('myArray') as FormArray
}

then you can ask about myFormArray.at(i).valid. e.g.

add(index)
{
    if (this.myFormArray.at(index).valid)
       this.myFormArray.add(new FormGroup({...}))
    else
       (this.myFormArray.at(index) as FormGroup).markAsTouched()
}

NOTE: by defect a mat-error is showed when the FormControl is not valid and touched