【问题标题】:Angular: Use Renderer 2 to Add CSS VariableAngular:使用 Renderer 2 添加 CSS 变量
【发布时间】:2018-08-01 16:03:50
【问题描述】:

是否可以使用 Renderer2 添加内联样式 css 变量?

我尝试了以下方法,但它不起作用。

import { Component, OnChanges, Output, ViewChild, Renderer2, ElementRef, ViewEncapsulation } from '@angular/core';

@Component({
})
export class CollapsibleComponent implements OnChanges {

  @ViewChild('collapsibleContent') collapsibleContent: ElementRef;

  constructor(
    private renderer: Renderer2
  ) { }

  ngOnChanges() {
    this.measureCollapsibleContents()
  }

  measureCollapsibleContents() {
    this.renderer.setStyle(this.collapsibleContent.nativeElement, '--expanded', this.collapsibleContent.nativeElement.firstElementChild.offsetHeight + 'px' )
  }

}

'--expanded' 不是适当的 css 属性,因此 angular 不会向我的 div 添加任何样式。

如果我添加了适当的 css 属性,它将像下面的代码一样工作。

this.renderer.setStyle(this.collapsibleContent.nativeElement, 'top', this.collapsibleContent.nativeElement.firstElementChild.offsetHeight + 'px' )

我的 div 的输出将是

<div style="top: 160px">...</div>

我想实现以下目标

<div style="--expanded: 160px">...</div>

我也尝试过[ngStyle],但除了样式属性之外,它也不会呈现任何值。

[ngStyle]="{'--expanded': expandedHeight }"

输出到

<div style>...</div>

【问题讨论】:

    标签: angular css-variables angular-renderer


    【解决方案1】:

    Angular 会清理属性绑定中设置的 CSS 变量。您可以使用 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

    您可能会觉得这个article 很有趣。它详细介绍了使用 CSS 变量对 Angular 组件进行主题化。

    【讨论】:

    • 我想在使用相同的渲染器添加触发转换的类之前使用 Renderer2 设置 css 变量。您将如何将 bypassSecurityTrustStyle 与 renderer.setStyle 一起使用?
    猜你喜欢
    • 1970-01-01
    • 2013-04-06
    • 2021-08-08
    • 2017-02-08
    • 2016-06-05
    • 1970-01-01
    • 2017-04-10
    • 2017-06-09
    • 2018-07-01
    相关资源
    最近更新 更多