mr_blond
mr_blond

Reputation: 1730

How do I change ngStyle dynamically?

I need to change multiple styles when some variable changes.

I can use something like:

[style.left]="isMenuShown ? '0px' : '-100vw'"

it works fine, but I wish to change multiply styles.

And I try to use ngStyle example:

<div [ngStyle]="styleList">...</div>

And in controller something like:

if (this.isDefaultStyle) {
    this.styleList = {'background' : 'green'};
  } else {
    this.styleList = {'background' : 'red'};
  }

It seems like it works, but when I inspect it with f12 I see

ng-reflect-ng-style="[object Object]"

Thereby question is: does it mean it is not working correctly? And if yes what is the correct way for me to change ngStyle dynamically?

Upvotes: 1

Views: 5350

Answers (4)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

You can use ngStyle like this

<div [ngStyle]="{'background' : isDefaultStyle ? 'green' : 'red'}">...</div>

Upvotes: 0

לבני מלכה
לבני מלכה

Reputation: 16251

Use ngClass instead ngStyle

<div [ngClass]="{isMenuShown ? 'show' : 'hide'}">...</div>

in css:

.show{multi style when show menu}
.hide{multi style when hide menu}

Upvotes: 3

Sunil
Sunil

Reputation: 11243

You can use function to accomplish the dynamic variations.

<div [ngStyle]="getStyleList()">...</div>

In controller

function getStyleList(){
 if (this.isDefaultStyle) {
       return {'background' : 'green'};
  } else {
      return {'background' : 'red'};
  }
}

Upvotes: 0

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

Use ngClass instead of ngStyle as you need to change multiple styles.

Here is an example:

    <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

    <some-element [ngClass]="{'class1': var1===1, 'class2': var1===2, 'class3': var1===3}">...</some-element>

    <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

Description:

Inside ngClass object: The key is a class name and the value is condition.

Upvotes: 1

Related Questions