Here is a solution that can cover if you want to pass multiple css styles as string or as object with cammelCase conventions:
Parent HTML
<app-button [style]="styleFromParent">Some button</app-button>
Parent component has styleFromParent property and it has simulation if that property is changed at some point:
Parent Component TS
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-site-panel',
templateUrl: './site-panel.component.html',
})
export class SitePanelComponent implements OnInit {
constructor(private _detectChanges: ChangeDetectorRef) {}
styleFromParent = { marginTop: '10px', marginLeft: '50px' };
ngOnInit() {
setTimeout(() => {
this.styleFromParent = { marginTop: '20px', marginLeft: '1px' };
this._detectChanges.detectChanges();
}, 2000);
}
}
Child HTML
<ng-content></ng-content>
Child Component TS
In child component part that does parsing if typeof style === 'object' is to parse cammelCase styles into dash based styles and concat them into one line string.
import { Component, OnInit, HostBinding, Input } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';
@Component({
selector: 'app-button',
templateUrl: './button.component.html',
})
export class ButtonComponent implements OnInit {
@HostBinding('style') baseStyle: SafeStyle;
@Input()
set style(style: string | object) {
let mappedStyles = style as string;
if (typeof style === 'object') {
mappedStyles = Object.entries(style).reduce((styleString, [propName, propValue]) => {
propName = propName.replace(/([A-Z])/g, matches => `-${matches[0].toLowerCase()}`);
return `${styleString}${propName}:${propValue};`;
}, '');
this.baseStyle = this.sanitizer.bypassSecurityTrustStyle(mappedStyles);
} else if (typeof style === 'string') {
this.baseStyle = this.sanitizer.bypassSecurityTrustStyle(mappedStyles);
}
}
constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {}
}
Above you can see that baseStyle has HostBinding to style component binding.
When style input is passed setter will triger, check if string or object is passed, parse it to string and sanitize that css and assign it to baseStyle thus host style will change.
EDIT:
As @Scorpioo590 said, this is replacable with [ngStyle].
So this seems unneeded. Maybe at least this can show what can you do with style and HostBinding.