1

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 ?

1 Answer 1

4

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)));
Sign up to request clarification or add additional context in comments.

4 Comments

Bless you. I didn't know there is such thing as NgZone. It works like a charm. I will accept your answer when it will be possible.
yea, just be careful, this looks like you have a little bit of a memory leak if you're never removing that event listener
Oh, thank you for the advice. Is removing it in the ngDestroy enough ? There is a method for it in the library documentation: colorPicker.off('color:change', onColorChange);
ngOnDestroy is the correct place to do it in most cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.