How to pass Object to NgStyle directive in Angular 2?

Emmanuel Villegas picture Emmanuel Villegas · Nov 9, 2016 · Viewed 9.2k times · Source

I'm trying to use NgStyle directive with an object variable like so:

@Component({
      template: `
            <div [ngStyle]="object">
              some test text
           </div>`
    })

export class example {
    private object: string = "{background-color: 'white'}";
}

I also tried with object = "background-color: 'red'" and [ngStyle]="{object}", but it seems like it doesn't work. I get the message error:

Error: Uncaught (in promise): Error caused by: Cannot find a differ supporting object '{color: 'white'}'(…)consoleError @ VM1051 [email protected]?main=browser:346_loop_1 @ VM1051 [email protected]?main=browser:371drainMicroTaskQueue @ VM1051 [email protected]?main=browser:375ZoneTask.invoke @ VM1051 [email protected]?main=browser:297

What am I doing wrong?

Answer

Stefan Svrkota picture Stefan Svrkota · Nov 9, 2016

Don't pass a string to [ngStyle], pass an Object and it will work:

private object: Object = { 'background-color': 'red'};