How can I help you?
Two-way binding in Angular Color picker component
26 Feb 20264 minutes to read
The ColorPicker component supports two-way property binding, allowing the color value to synchronize between the ColorPicker and other components in real time.
Implementing two-way binding
-
Create a ColorPicker component and bind the
valueproperty using two-way binding as shown in the following code snippet.<input ejs-colorpicker type="color" class="form-control" id="colorpicker" required [(value)]="value" name="colorpicker" /> -
Create a text input and bind the same value property using
ngModel.<input type="text" id="name" name="name" class="form-control" [(ngModel)]="value" /> -
Use the same variable name in both the ColorPicker and text input. This synchronizes the value: changing the color in the ColorPicker updates the text input, and editing the text input updates the ColorPicker.
-
Initialize the variable value in the component file. This value is bound to both the ColorPicker and text input. Any change to either component automatically updates the other.
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { ColorPickerModule } from '@syncfusion/ej2-angular-inputs'
import { FormsModule } from '@angular/forms'
import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Browser } from '@syncfusion/ej2-base';
@Component({
imports: [
ColorPickerModule,
FormsModule
],
standalone: true,
selector: 'app-root',
templateUrl: './template.html',
styleUrls:['./index.css']
})
export class AppComponent {
private cValue: string = "#1de4d7";
get value(): string {
if (Browser.info.name === 'msie' && this.cValue.length > 7) {
return this.cValue.substring(0, this.cValue.length - 2);
} else {
return this.cValue;
}
}
@Input('value')
set value(value: string) {
this.cValue = value;
}
}<div class="container">
<form #colorPickerForm="ngForm">
<div class="form-group">
<label for="color">The selected color value is:</label>
<br/>
<div class="wrap">
<input type="text" id="color" name="color" class="form-control" spellcheck="false" [(ngModel)]="value" required>
<ejs-input ejs-colorpicker type="color" class="form-control" id="colorpicker" required [(value)]="value" name="colorpicker" />
</div>
</div>
</form>
</div>import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));By default, the selected color value returns an 8-digit hex code (with alpha channel) in the
valueproperty. Some browsers, such as Internet Explorer, do not support 8-digit hex codes. In such cases, use getter and setter methods to convert the value to a compatible format, as shown in the sample above.