Search code examples
htmlcssangularngforng-class

Assigning background-color & border-color to buttons dynamically in angular


I have an array of colors,

colors = ['red', 'green', 'blue', 'yellow', 'black']

Also, I have an array like this

demo = ['de1', 'de2', 'de3', 'de4', 'de5', 'de6', 'de7', 'de8', 'de9', 'de10', 'de11', 'de12', 'de13', 'de14'] 

and so on, which is dynamic, which I get in response from an API call from which I'm preparing buttons.

I need to assign the background-color and border-color from the colors [] to each element in demo [] in the same order. Need help on this.

TIA


Solution

  • Really you not have elements in your array demo (your array is an array of strings)

    <!--imagine an array of "items"-->
    <div *ngFor="let item of items">
      .....
    </div>
    

    You can then use some like

    <div *ngFor="let item of items;let i=index">
      <div [style.color]="colors[i%5]">I'm in color {{colors[i%5]}}</div>
    </div>
    

    You can also use ViewChildren

    <div *ngFor="let item of items;let i=index">
      <div #dd>I'm in color {{colors[i%5]}}</div>
    </div>
    

    And in your .ts

    @ViewChildren('dd') items:QueryList<ElementRef>
    ngAfterViewInit()
    {
       this.items.forEach((x:ElementRef,i:number)=>{
              x.nativeElement.style.color=this.colors[i%5]
       })
    }