如何在Angular组件的样式标签中使用字符串插值?

S. *_*son 8 css string interpolation styles angular

@Component({
  selector: 'app-style',
  template: `
    <style>
      .test {
        color: {{ textColor }}
      }
    </style>
  `
})
export class StyleComponent {
  textColor = "red";
}
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用,我需要我的样式是动态的,并在一些特定的CSS类.还有其他方法可以做到这一点吗?

mal*_*awi 6

当组件被渲染时,style 标签将移动到页面的 head 元素,并且该元素内的任何 angular 语法都将被忽略。

我发现的唯一方法是动态创建样式元素并提供所需的样式。

app.component.ts

  textColor = 'red';
  constructor(private el: ElementRef) {

  }

  ngOnInit() {

    let style: string = `
     .test {color :${this.textColor}; }
    `;

    this.createStyle(style);

  }

  createStyle(style: string): void {
    const styleElement = document.createElement('style');
    styleElement.appendChild(document.createTextNode(style));
    this.el.nativeElement.appendChild(styleElement);
  }
Run Code Online (Sandbox Code Playgroud)

应用模板.html

<span class="test">test</span>
Run Code Online (Sandbox Code Playgroud)

堆叠闪电战演示


Alp*_*zkn 5

您可以像这样使用 ngStyle 指令;

@Component({
  selector: 'app-style',
  template: `
   <ul>
      <li [ngStyle]="{color: textColor}">List Item</li>
   </ul>
  `
})
export class StyleComponent {
  textColor = "red";
}
Run Code Online (Sandbox Code Playgroud)


ibe*_*oun 3

您可以通过[style.color]在样式表中指定定义的类来访问颜色样式[class]

<div [style.color]="color">Style Test</div>
<div [class]="className">Class Test</div>
Run Code Online (Sandbox Code Playgroud)

这是一个运行示例。