Inject Style Declarations Using Hostbinding in Angular
18,010
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) {}
Related videos on Youtube
Author by
Andrei Voicu
Updated on June 04, 2022Comments
-
Andrei Voicu almost 2 years
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';
but I would like to do it for all of them, please help :P
this is the full code:
@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() {} }
and a working plunker: https://plnkr.co/edit/CVglAPAMIsdQjsqHU4Fb?p=preview
-
Ben Taliadoros about 6 yearsThe plunker says /* this does not work */, any update
-
Günter Zöchbauer about 6 yearsCopying to a new Plunker would probably do to get the Angular version updated. I'll have a look when I have a bit of time (no guarantees)
-
Thilak Rao about 6 years@BenTaliadoros Demo was broken. Fixed it.
-
Thilak Rao about 6 years@GünterZöchbauer Yes, here you go - stackblitz.com/edit/style-hostbinding-demo
-
Zengineer almost 5 yearsHow can you set multiple definitions for the same style, e.g.
cursor: grab; cursor: -webkit-grab
-
Günter Zöchbauer almost 5 yearsI don't think you can. Better to set/clear a class and use CSS instead.