Contact Support
Two way binding in Angular Color picker component
5 Dec 20243 minutes to read
ColorPicker component supports two-way property binding.
The steps to perform two-way binding.
-
Create ColorPicker component and binds the
value
property as like the below code snippet.<input ejs-colorpicker type="color" class="form-control" id="colorpicker" required [(value)]="value" name="colorpicker" />
-
Create text box and bind the value using ngModel.
<input type="text" id="name" name="name" class="form-control" [(ngModel)]="value" />
-
And name the same variable name in both color picker and text box. Which will help to view the two-way binding i.e. changing value in color picker will change the textbox value and vice versa.
-
Initialize the value of the variable in component file, while will be bound to color picker and text box initially. The values will be changed synchronously while changing any one (color picker or text-box) value.
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 8 digit hex code in
value
property. Some browser like IE won’t support the 8 digit hex code. In such case, you can use getter setter method to change the value to supported format as like the above sample.