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
HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive. @HostBinding - will bind the property to the host element, If a binding changes, HostBinding will update the host element.
@HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.
HostBindinglinkAngular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.
@HostBinding('class. valid') isValid; Binds a host element property (here, the CSS class valid) to a directive/component property (isValid).
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) {}
working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With