Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngStyle for multiple styles

Tags:

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.

like image 639
Christopher Avatar asked Jun 09 '17 14:06

Christopher


People also ask

Can you have multiple ngStyle?

With style binding we can set only a single style, however to set multiple styles we can use ngStyle directive.

Can we use NgClass and ngStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

What type of directive is ngStyle?

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 .


Video Answer


1 Answers

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 {}    } } 
like image 118
Hamed Baatour Avatar answered Sep 30 '22 20:09

Hamed Baatour