角度:使用Renderer 2添加CSS变量 [英] Angular: Use Renderer 2 to Add CSS Variable

查看:411
本文介绍了角度:使用Renderer 2添加CSS变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我尝试了以下操作,但不起作用.

I tried the following but it doesn't work.

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添加任何样式.

'--expanded' isn't a proper css property so angular won't add any style to my div.

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

If I do add a proper css property it will work like the code below.

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],但是除了style属性,它也没有呈现任何值.

I have also tried [ngStyle] but that also doesn't render any value but the style attribute.

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

输出到

<div style>...</div>

推荐答案

Angular清除了在属性绑定中设置的CSS变量.您可以使用DomSanitizer绕过此行为.

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;
    }
  }
}

实时演示

您可能会发现文章很有趣.它详细介绍了如何使用CSS变量为Angular组件设置主题.

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

这篇关于角度:使用Renderer 2添加CSS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆