Change the color of the TextBox based on its value in Angular

26 Oct 20242 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 { FormsModule } from '@angular/forms'
import { Component } from '@angular/core';
import { TextBoxModule } from '@syncfusion/ej2-angular-inputs';

@Component({
imports: [
        TextBoxModule,
        FormsModule
    ],
standalone: true,
    selector: 'app-root',
    template: `<div class="wrap">
                <label> Normal Input </label>
                    <ejs-textbox 
                    placeholder = "Enter numeric values" (keyup)="onKeyup($event)"></ejs-textbox>
                 <label> Floating Input </label>
                 <ejs-textbox 
                    placeholder = "Enter numeric values" floatLabelType="Auto" (keyup)="onKeyup($event)"></ejs-textbox>
              </div>`
})

export class AppComponent {
    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 { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));