Angular ngStyle for multiple styles
I'm working on a simple animation library where my user can modify my component using property binding, so so far I've done the following to apply their selection:
<div [style.background]="color" [style.width.px]="width" [style.height.px]="height"></div>
But for future additions I want to change this whole mess with [ngStyle]="styleObject"
to make it easier to add additional properties, I am trying to achieve it something like this:
@Input() width: number;
@Input() height: number;
public styleObject: Object = {
'height': this.height,
'width': this.width
};
But for some reason <div [ngStyle]="styleObject"></div>
does not take into account the style shown above.
Please note that adding + 'px'
and doing height.px
doesn't solve my problem.
What can't I see?
-
Several tests have shown that
styleObject = {
'height': 200 + 'px',
'background': 'red'
};
works and applies to div
, but replacing 200
with this.height
(type number
) doesn't.
source to share
When you use ngStyle
you must create a function that returns one of the following: string, array, or object.
if you want to return an object you do the following:
in your template:
<div [ngStyle]="styleObject()"></div>
in your component:
export class AppComponent{
styleObject(): Object {
if (/** YOUR CONDITION TO SHOW THE STYLES*/ ){
return {height: this.height,width: this.width}
}
return {}
}
}
source to share
If you define your styleObject
then this.height
and this.width
will be undefined. At least, determine styleObject
in ngOnInit
where bindings are guaranteed to be initialized.
For a more dynamic experience where the user can change properties after the component has rendered, you can use getters / setters.
It will look something like this:
export class YourComponent {
styleObject: {[key: string]: string} = {};
@Input()
set width(w: string) {
styleObject = Object.assign({}, styleObject, {width: w});
}
get width() { return styleObject.width; }
@Input()
set height(h: string) {
styleObject = Object.assign({}, styleObject, {height: h});
}
get height() { return styleObject.height; }
}
Actually you are probably omitting getters.
source to share