问题
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:
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;
}
来源:https://stackoverflow.com/questions/49697772/set-css-variable-with-html5-color-picker-in-angular-5