In this article, we will learn max length Directive in Angular.
Step 1:-
Create an Angular application using this command
ng new demo cd demo
Step 2:-
Create a Component in your project using this component
ng generate directive max-length
Add the following code in your max-length directives
import { Directive, HostListener, Input, ElementRef } from '@angular/core' import { NgControl } from '@angular/forms' @Directive({ selector: '[appMaxLength]', }) export class MaxLengthDirective { @Input() maxLength!: number constructor(private element: ElementRef, public model: NgControl) {} @HostListener('input', ['$event']) onEvent() { let value: string = this.element.nativeElement.value let newVal: any if (!value) { newVal = undefined } else if (value.length > this.maxLength) { value = value.slice(0, this.maxLength - value.length) } newVal = value this.model?.control?.setValue(newVal) } }
Step 3:-
Add following code to app.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { userForm: FormGroup | any constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ name: ['', Validators.required], contactNo: ['', [Validators.required, Validators.minLength(10)]], }) } ngOnInit(): void { } }
Step 4:-
Add following code to app.component.html
<form name="artistForm" [formGroup]="userForm"> <label>Name : </label> <input type="text" name="name" formControlName="name" appMaxLength [maxLength]="100"/> <br> <label>Contact No : </label> <input type="text" name="contactNo" formControlName="contactNo" appNumberOnly/> </form>
Step 5:-
npm start