Angular: Use Renderer 2 to Add CSS Variable

前端 未结 1 1783
失恋的感觉
失恋的感觉 2021-01-15 12:14

Is it possible to add inline style css variable using Renderer2?

I tried the following but it doesn\'t work.

import { Component, OnChang         


        
相关标签:
1条回答
  • 2021-01-15 12:43

    Angular sanitizes CSS variables set in property bindings. You can bypass this behavior with DomSanitizer.

    @Component({
      selector: 'my-app',
      template: `
        <button (click)="dec()">-</button>
        <button (click)="inc()">+</button>
    
        <div [style]="style"> My height is set by CSS Variable </div>
      `,
      styles: [`
        div {
          height: var(--height);
        }
        `
      ]
    })
    export class AppComponent {
      height = 50;
    
      get style() {
        return this.sanitizer.bypassSecurityTrustStyle(`--height: ${this.height}px`);
      }
    
      constructor(private sanitizer: DomSanitizer) { }
    
      inc() {
        this.height += 10;
      }
    
    
      dec() {
        this.height -= 10;
        if (this.height <= 0) {
          this.height = 0;
        }
      }
    }
    

    Live demo

    You might find this article interesting. It goes into details on theming Angular components with CSS variables.

    0 讨论(0)
提交回复
热议问题