How to put character limit on a mat Input?

dota2pro picture dota2pro · Sep 17, 2019 · Viewed 20.1k times · Source

I didn't find any mention of character limit in the docs. Seems like a very common requirement.

How Can I add a 300 characters limit to this Textarea ?

https://stackblitz.com/edit/angular-izbcey?file=app/input-overview-example.ts

Answer

Zulqarnain Jalil picture Zulqarnain Jalil · Sep 17, 2019

You can use like this for text

<mat-form-field hintLabel="Max 300 characters">
<input matInput #input maxlength="300" placeholder="Enter some input">
<mat-hint align="end">{{input.value?.length || 0}}/300</mat-hint>
</mat-form-field>

for textarea

<mat-form-field hintLabel="Max 10 characters">
  <textarea #txtarea matInput  [maxLength]="10" [placeholder]="label"></textarea>
 </mat-form-field>