Issue
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.
Solution
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 {}
}
}
Answered By - Hamed Baatour
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.