Change the color of the textbox based on its value in Angular Textbox component

28 Sep 20233 minutes to read

You can change the color of the TextBox by validating its value using regular expression in the keyup event for predicting the numeric values as demonstrated in the following code sample.

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: `<div class="wrap">
                <label> Normal Input </label>
                <div class="e-input-group">
                    <input class="e-input" type="text" (focus)="focusIn($event.target)"
                    placeholder = "Enter numeric values" (blur)="focusOut($event.target)" (keyup)="onKeyup($event)"/>
                </div>
                 <label> Floating Input </label>
                <div class="e-float-input">
                    <input type="text"(focus)="focusIn($event.target)" (blur)="focusOut($event.target)" (keyup)="onKeyup($event)" required/>
                    <span class="e-float-line"></span>
                    <label class="e-float-text">Enter numeric values</label>
                </div>
              </div>`
})

export class AppComponent {
    public focusIn(target: any): void {
        target.parentElement.classList.add('e-input-focus');
    }

    public focusOut(target: any): void {
        target.parentElement.classList.remove('e-input-focus');
    }
    public onKeyup(event: any): void {
    let str = event.target.value.match(/^[0-9]+$/);
    if (!((str && str.length > 0)) && event.target.value.length) {
       event.target.parentElement.classList.add('e-error');
    } else {
      event.target.parentElement.classList.remove('e-error');
    }
  }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        FormsModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);