Search code examples
javascriptangularcolor-picker

Angular 8 retrieve value from external library


I have an Angular 8 application and I have imported the iro.js library into my project.

It is a JavaScript color picker library.

The usage is pretty basic:

I have updated scripts in angular.json

"scripts": 
[
    "node_modules/@jaames/iro/dist/iro.js"
]

and then used the library as follows

declare var iro: any;
   .
   .
   .
ngOnInit() {
    this.colorPicker = new iro.ColorPicker('#color-picker-container');
    this.colorPicker.on('color:change', this.onColorChange);
}

onColorChange(color, changes) {
    this.selectedColor = color.hexString;
    console.log(this.selectedColor);
}

Even though the value gets printed out, the value did not actually change.

I have a div element that uses this variable to display the color, but it doesn't change.

<div class="color-value" [style.background-color]="selectedColor"></div>

I have also tried calling the ChangeDetectorRef.detectChanges() method, but it says that iro.js cannot call detectChanges() of undefined (since the ChangeDetectorRef is injected in the component constructor and the library doesn't know about it).

Any ideas how to retrieve the color hex value from the library into my Angular component ?


Solution

  • iro.js isn't running in ngZone, inject it and use it to run your function to change detection works correctly:

    constructor(private ngZone: NgZone) {}
    
    this.colorPicker.on('color:change', (color, changes) =>  this.ngZone.run(() => this.onColorChange(color, changes)));