No Space Starting In Textbox Using Angular

In this article, we will learn like who we can validate the input field value does not start with space using the directive.

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 no-space-starting

Add the following code in your no-space-starting directives

import { Directive, HostListener, Input, ElementRef } from '@angular/core'
import { NgControl } from '@angular/forms'

@Directive({
  selector: '[noSpaceStartingOnly]',
})
export class NoSpaceStartingDirective {
  constructor(private element: ElementRef, public model: NgControl) {}

  @HostListener('input', ['$event'])
  onEvent() {
    let value: string = this.element.nativeElement.value

    if (value && value.startsWith(' ')) {
      this.model?.control?.setValue(value.trim())
    } else {
      this.model?.control?.setValue(value)
    }
  }
}

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" noSpaceStartingOnly/>
    <br>
    <label>Contact No : </label>
    <input type="text" name="contactNo"  formControlName="contactNo" noSpaceStartingOnly/>
</form>

Step 5:-

npm start

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories