How to change a value in CSS using TypeScript?

Tags: , , ,



I want to make an <input> text box where you write a certain color, say 'red' and a certain text gets colored like that. I found some guidelines on how to do it, but the code is in JavaScript, instead of TypeScript. So far I got this:

HTML

<input id="color" />
<h1>Change the color</h1>

CSS

<style>
h1 {
   color: var(--color, blue)
}
</style>

JavaScript

const color = document.querySelector('#color');
color.addEventListener('input', e => {
document.documentElement.style.setProperty('--color', color.value)
})

As I am using .ts classes, I am wondering how can the JavaScript above be written instead?

Answer

To achieve that you should read the value of input (let’s use two-way binding via [(ngModel)] directive), and then just use this value to apply as a style rule ([style.color] fits perfectly for this). And finally, you should end up with just a few lines of code:

HTML:

<input [(ngModel)]="color" />
<h1 [style.color]="color">Change the color</h1>

TS:

export class AppComponent  {
  color: string;
}

Here is a STACKBLITZ.

I also defined a default blue color in CSS just for example. This works as a default color because style rules defined via style attribute have a higher priority in this case.

UPDATE

If you want to control the color of all the elements over your app, you can use @HostBinding('style') at the top-level component this way:

export class AppComponent  {
  color: string;

  @HostBinding('style')
  get myStyle(): SafeStyle {
    return this.sanitizer.bypassSecurityTrustStyle(`color: ${this.color};`);
  }

  constructor(private sanitizer:DomSanitizer) {}
}

Here is a STACKBLITZ.

enter image description here



Source: stackoverflow