我有一个简单的 Angular 组件。
@Component({
selector: 'app-component-test',
templateUrl: './component-test.component.html',
styles: [example],
encapsulation: ViewEncapsulation.None,
providers: []
})
我想从组件类内部更新样式。我怎样才能实现这个目标?
最佳答案
这有点hacky,但这是一个可能的解决方案。如果您不希望样式泄漏到应用程序中的其他组件(但对于子组件来说没问题),您可以在样式前面添加 Angular 添加的 _ngHost-*****
属性到组件。
所以你的规则看起来像
[_nghost-ybl-c433] p { color: red;}
[_nghost-ybl-c433] h1 { color: blue;}
组件.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 来添加前缀,则必须在客户端执行此操作...
关于angular - 如何动态更新Angular组件的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61503525/