0

I have an Angular 5 application with items styled in CSS with CSS variables, as in

--color-links: #0000ff;
a { color: var(--color-links); }

So, I was trying to wire up an HTML5 color picker to allow changing this variable on the fly.

I saw this article which showcases this pen where the author is using some simple JS to do something like I am trying to do, but with document.addEventListener. I was trying to come up with a pure Angular/HTML5 method.

So, I created a picker:

    <div class="form-group">
        <label for="color-picker-link">Link color</label>
        <input type="color"
               id="color-picker-link"
               (change)="setColor()"
               [(value)]="linkColor">
      </div>

And in my Component, I create the variable linkColor and setting it to #0000ff. That part works, the picker defaults to blue.

public linkColor = '#0000ff';
setColor() {
  console.log('value', this.linkColor);
}

However, the variable always logs as the original 30000ff even though the picker obviously changes.

So, what I need to do is get the value the picker was changed to. Not sure why it's not working.

Also, the sample Codepen I linked to above uses this function to set the variable value once retrieved, although I don't think it would work in an Angular app:

function setThemeVar(name, value, unit) {
  var rootStyles = document.styleSheets[0].cssRules[0].style;
  rootStyles.setProperty('--theme-' + name, value + (unit || ''));
}

If I can solve getting the value from the picker on change, and then fire a function passing that retrieved value I can probably figure out the rest.

1 Answer 1

1

To get the selected value from the picker use ngModelChange event with ngModel directive.

<input type="color"
               id="color-picker-link"
               (ngModelChange)="setColor($event)"
               [ngModel]="linkColor">

setColor(newColor) {
  console.log('value', newColor);
  this.linkColor = newColor;
}
Sign up to request clarification or add additional context in comments.

Comments

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.