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'

  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(' ')) {
    } else {

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

Step 5:-

npm start

Submit a Comment

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


Select Categories