如何动态更新角度组件的样式 [英] How to update styles of Angular Component dynamicaly

查看:65
本文介绍了如何动态更新角度组件的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Angular组件.

I have a simple Angular Component.

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

我想从组件类内部更新样式.我该如何实现?

I want to update the styles from inside the component class. How can I achieve this?

推荐答案

这有点棘手,但这是可能的解决方案.如果您不希望样式泄漏到应用程序中的其他组件(对于子组件来说也可以),则可以在您的样式前面加上_ngHost-*****属性,该属性将angular添加到组件中.

This is a bit hacky, but here is a possible solution. If you don't want your styles to leak to other components in your application (but it's ok for child components), you can prefix your styles with the _ngHost-***** attribute that angular adds to components.

所以您的规则看起来像

[_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以添加前缀,则必须在此客户端进行操作...

If you cannot modify the API to add the prefix, you'll have to do this client side...

Stackblitz演示

这篇关于如何动态更新角度组件的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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