Search results

Change the Color of the TextBox Based on its Value in Angular TextBox component

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.

Source
Preview
app.component.ts
app.module.ts
main.ts
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: HTMLElement): void {
        target.parentElement.classList.add('e-input-focus');
    }

    public focusOut(target: HTMLElement): void {
        target.parentElement.classList.remove('e-input-focus');
    }
    public onKeyup(event): 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';

enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);