Max Length Directive In Angular

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'

  selector: '[appMaxLength]',
export class MaxLengthDirective {
  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


Step 3:-

Add following code to app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
export class AppComponent {

  userForm: FormGroup | any

  constructor(private fb: FormBuilder) {
    this.userForm ={
      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"/>
    <label>Contact No : </label>
    <input type="text" name="contactNo"  formControlName="contactNo" appNumberOnly/>

Step 5:-

npm start

Submit a Comment

Your email address will not be published.


Select Categories