How to put character limit on a mat Input?
Asked Answered
E

2

18

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

Edmundson answered 17/9, 2019 at 14:52 Comment(1)
if you are using reactive forms use Validators.maxLength, else use maxLength attribute on textarea tagsHassler
L
55

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>
Lowther answered 17/9, 2019 at 14:57 Comment(1)
Can you explain how the value counter is working inside mat-hint?Tlingit
D
-1
const MAX_VALIDATOR: any = {
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => MaxValidatorDirective),
  multi: true,
};

@Directive({
  selector: '[max][formControlName],[max][formControl],[max][ngModel]',
  providers: [MAX_VALIDATOR],
})
export class MaxValidatorDirective implements Validator {
  @Input() maxInput: number;

  validate(c: AbstractControl): {[key: string]: any} {
    return this.max(this.maxInput)(c);
  }

  max(testValue: number, ignoreNan = true) {
    return (control: AbstractControl): {[key: string]: any} => {
      let value = parseFloat(control.value);
      if (ignoreNan && isNaN(value)) {
        return null;
      } else {
        return value <= testValue ? null : {'max': {value}};
      }
    }
  };
}

You need to make a directive like that and you can use it

Dyestuff answered 17/9, 2019 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.