I am working on a simple animation library where my user can modify my component using property binding, so far I have been doing the following to apply their choices:
<div [style.background]="color" [style.width.px]="width" [style.height.px]="height"></div>
But for future additions I wish to change this whole mess with [ngStyle]="styleObject"
to simplify adding more properties, I am trying to achieve this like such:
@Input() width: number; @Input() height: number; public styleObject: Object = { 'height': this.height, 'width': this.width };
But for some reason <div [ngStyle]="styleObject"></div>
is not taking into account the style shown above.
Please note that adding + 'px'
and doing height.px
does not solve my issue.
What am I not seeing?
--
A few tests have shown that
styleObject = { 'height': 200 + 'px', 'background': 'red' };
works and is applied to the div
, but that replacing 200
with this.height
(of type number
) does not.
With style binding we can set only a single style, however to set multiple styles we can use ngStyle directive.
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
NgStylelinkAn attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional .
When you using ngStyle
you should create a function returning one of the following: a string, an array or an 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 {} } }
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