Search code examples
angularelementref

Angular 4 dynamic style update for dynamic ids


I have a number of dynamic "divs" each with their own dynamic "id" from database. In the background there's a service running in intervals of 15 seconds, each time pulling new data and updating the status which will be represented with a different background colour per div.

PS - i am able to do it for a specific "id" (easy), just stuck on how to do it for dynamic "id" with dynamic background colours.

NOTE: The "divs" are randomly located on the page, therefore, doing a loop on the "div" with "ngFor" won't work.

e.g.

<div id="xxx12312" [style.background-color]="dynamicColor">1. Some data</div>
<div id="yyadsfas" [style.background-color]="dynamicColor">2. Some more data</div>
<div id="00012123" [style.background-color]="dynamicColor">3. Some even more data</div>

Ideally i would have the following inside the component with a loop to iterate over the json object like so:

for(let v of rows) {
    this.elementId(v.dynId).style = v.color
}

Any help is much appreciated. Cheers in advance.


Solution

  • inject ElementRef in your constructor and then you can use it to grab the dom element.

    if your dynamic data something like below

    [ { "id": "abc", "color": "red", "content": "1st div" }, { "id": "pqr", "color": "green", "content": "2nd div" }, { "id": "xyz", "color": "blue", "content": "3rd div" } ]
    

    then loop your dynamic data to set the color and content of div.

    this.dynamicData.forEach(
    x=>{
    this.elRef.nativeElement.querySelector('#'+x.id).style.color = x.color;
    this.elRef.nativeElement.querySelector('#'+x.id).innerHTML = x.content;
    }
    )