Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Driven Form Validation on Text area

I added a text area to my angular form. all the input/mat-select fields work fine with the requried attribute. For the textarea I added a custom class to show a red border. For some reason when I click the clear button the two input fields automatically applies its own red class but my custom class for the texareaa does not unless it has been touched. Which is fine but does not match the styles of the input fields. How do I apply the same validation styles to the text area: https://stackblitz.com/edit/angular-mpefsn

.text-error.ng-invalid.ng-touched{
  border: 1px solid #b00b00;
}

If you click on the clear button initially when the stack blitz loads you will see the two inputfields turn red but not the textarea. This is because I have the ngtouched class. But if I remove it then the textarea will initially be red.

like image 615
Flash Avatar asked Feb 27 '26 16:02

Flash


1 Answers

The easiest way would to just use matInput with the textarea

<mat-form-field>
  <textarea matInput ...></textarea>
</mat-form-field>

then you would have the same style for all the input fields. And material would apply red because it is required.

The harder way, if you want the textarea to be of different style could be to manually add a class to the textarea field.

.ts file:

public cleared = false;
...
clear() {
  ..
  this.cleared = true;
}

and in your html:

<textarea [(ngModel)]="inputValue" [class.custom_invalid_form_class]="cleared && inputValue.length > 0"></textarea>
like image 164
Engam Avatar answered Mar 02 '26 07:03

Engam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!