quma
quma

Reputation: 5743

Angular5 - set color of div container dynamically

With AngularJS this worked fine:

<div style="width:10px;height:10px;background-color:{{user.color}}"></div>

but with Angular5 it doesn't. How to do it with Angular5?

Upvotes: 10

Views: 35571

Answers (4)

Vega
Vega

Reputation: 28738

<div style="width:10px;height:10px;" [ngStyle]="{'background-color': user.color}">...</div>

or

<div [style.background-color]="user.color">...</div>

Docs

How to use ngStyle

<some-element [ngStyle]="{'font-style': styleExp}">...</some-element>

<some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>

<some-element [ngStyle]="objExp">...</some-element>

Upvotes: 37

Pietro
Pietro

Reputation: 177

To dynamically change the color of a div with a Color Picker in Ionic 5: watch this video for making the color Picker: https://youtu.be/g4rQBQDUSJY Then do the following below:

in HTML

<div id="picker"></div>
        <br/>
        <div>
          <ion-text>
            Color hex: {{colorCodeHEX}}
          </ion-text>
          <br/>
        </div>


<div [style.background-color]="colorCodeHEX">&nbsp;</div>

if you remove the &nbsp; it doesn't work

in TS

import iro from '@jaames/iro';  



colorCodeHEX:string="";


 ngOnInit() {
    let ref = this;
    var colorPicker = iro.ColorPicker ("#picker",
    {width:this.width1,
      layout: [
        {
        component: iro.ui.Wheel,
        options: {}
        },
    ]
    });

    colorPicker.on('color:change',function(color)
    {
     ref.colorCodeHEX = color.hexString; 
    });
  }

Upvotes: 0

A. A.
A. A.

Reputation: 153

Rather than using inline css use class. You can use ngClass for that

[ngClass]="user.color"

pass the class name in property. So if you want to add more properties in css it will be easier then.

Upvotes: 0

Akash Sengar
Akash Sengar

Reputation: 149

You can use ngStyle or ngClass for doing it Dynamically.

Upvotes: 0

Related Questions