在Angular中使用主机绑定注入样式声明 [英] Inject Style Declarations Using Hostbinding in Angular
问题描述
你们知道我如何使用@HostBinding装饰器在组件中批量注入样式声明吗? 我正在尝试的是:
Do you guys know how I can batch inject style declarations in a component using the @HostBinding decorator? What I am trying is:
@HostBinding('style')
get style(): CSSStyleDeclaration {
return {
background: 'red',
color: 'lime'
} as CSSStyleDeclaration;
}
以我的理解,这应该为组件注入背景和颜色样式,但不是...
In my understanding this should inject the background and color style to the component, but it does not...
我可以像这样控制各个样式声明:
I can control individual style declarations like this:
@HostBinding('style.background') private background = 'red';
但是我想为所有人做,请帮助:P
but I would like to do it for all of them, please help :P
这是完整的代码:
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello world!</h2>
</div>
`,
})
export class App {
// This works
@HostBinding('style.color') private color = 'lime';
/* This does not work
@HostBinding('style')
get style(): CSSStyleDeclaration {
return {
background: 'red'
} as CSSStyleDeclaration;
}
*/
constructor() {}
}
和一个正在工作的矮人: https://plnkr.co/edit/CVglAPAMIsdQjsqHU4Fb?p=preview
and a working plunker: https://plnkr.co/edit/CVglAPAMIsdQjsqHU4Fb?p=preview
推荐答案
You need to pass the same value you would add to an element like <div style="...">
and sanitize the styles
@HostBinding('style')
get myStyle(): SafeStyle {
return this.sanitizer.bypassSecurityTrustStyle('background: red; display: block;');
}
constructor(private sanitizer:DomSanitizer) {}
这篇关于在Angular中使用主机绑定注入样式声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!