【问题标题】:How to update styles of Angular Component dynamicaly如何动态更新 Angular 组件的样式
【发布时间】:2020-04-30 16:12:13
【问题描述】:

我有一个简单的 Angular 组件。

@Component({
    selector: 'app-component-test',
    templateUrl: './component-test.component.html',
    styles: [example],
    encapsulation: ViewEncapsulation.None,
    providers: []
})

我想从组件类内部更新样式。我怎样才能做到这一点?

【问题讨论】:

  • 能否详细说明如何动态更新?
  • @RBC9662 把我带到了那里。希望我知道。这个想法是从 API 中获取 CSS 样式。并在组件初始化时设置样式(NOT INLINE)但 CSS 使用选择器等,与styles: [] 相同
  • 动态插入<style> 标签可能吗?还是<style> 链接?
  • 你真的需要设置 CSS 样式吗?设置 CSS 类也是一种选择吗?
  • @David 我想应用样式 css,只在那个组件上

标签: angular


【解决方案1】:

这有点老套,但这是一个可能的解决方案。如果您不希望您的样式泄漏到应用程序中的其他组件(但它可以用于子组件),您可以在样式前面加上 Angular 添加到组件的 _ngHost-***** 属性。

所以你的规则看起来像

[_nghost-ybl-c433] p { color: red;}
[_nghost-ybl-c433] h1 { color: blue;}

component.ts

constructor(private renderer: Renderer2, private elementRef: ElementRef) {}


private applyStylesFromAPI()
{
    //Find component prefix first
    let compPrefix = Array.from<Attr>(this.elementRef.nativeElement.attributes)
        .find(att=>att.nodeName.startsWith('_nghost')).nodeName;


    //Create style tag and add styles from API 
    let styleElt = this.renderer.createElement('style');

    styleElt.innerHTML = this.getAPIStyles(compPrefix);
    this.elementRef.nativeElement.appendChild(styleElt);
}

private getAPIStyles(compPrefix: string)
{
   //Retrieve the CSS styles from API, each rule prefixed with [compPrefix]

如果您无法修改 API 以添加前缀,则必须在客户端执行此操作...

Stackblitz demo

【讨论】:

    猜你喜欢
    • 2018-04-11
    • 2021-06-23
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2023-03-30
    • 2021-09-15
    • 2019-12-18
    • 2019-12-06
    相关资源
    最近更新 更多