简体   繁体   中英

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 texarea a 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.

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>

You could mark the textarea form control as touched when clicking on the clear button:

<textarea #txt="ngModel" [(ngModel)]="questionText" required ...></textarea>

<button (click)="clear(); txt.control.markAsTouched();" ...>Clear</button>

See this stackblitz for a demo.

The reason you are seeing the red border here for the other fields except for the textarea is because the other fields are getting their CSS from .mat-form-field-invalid . The .mat-form-field-invalid gets added to your mat-form-field because of this class which gets added when you submit the form without filling the required fields.

So do the same for your textarea , remove the text-error class as it's not required and add the matInput directive. Then just wrap your textarea in a mat-form-field like below

<mat-form-field>
    <textarea matInput name="questionText" cols="35" rows="8" placeholder="Question Text" [(ngModel)]="questionText" required></textarea>
</mat-form-field>

Here is a working example on StackBlitz .

Use the

<ion-textarea></ion-textarea>

instead of the native

<textarea></textarea>

in order to see validation results like with the

<ion-input></ion-input>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM