Search code examples
htmlcssangularangular-universalng-style

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?


Solution

  • Use ngClass instead ngStyle

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

    in css:

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