Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Object to NgStyle directive in Angular 2?

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?

like image 433
Emmanuel Villegas Avatar asked Nov 09 '16 19:11

Emmanuel Villegas


Video Answer


1 Answers

I had a similar issue with ngStyle, and fixed it as follows:

[ngStyle]="{'top.px':dtPickerTop, 'left.px':dtPickerLeft}"

dtPickerTop & dtPickerLeft are set in my component based on a click event.

Adding the .px made it work, whereas without it, it didn't seem to.

like image 62
Farasi78 Avatar answered Oct 05 '22 10:10

Farasi78