Angular 5 Material setting dynamic (random) colors

Issue

I have a lightweight carousel that is showing strings (questions) from an array. I want to change the background (and potentially the foreground) colors dynamically. However, my code is causing an error…

WARNING: sanitizing unsafe style value background:blue (see http://g.co/ng/security#xss).

  <ngx-carousel style="width:450px" layout="column" layout-align="center center" [inputs]="carouselOne" (carouselLoad)="myfunc($event)" flex>
    <ngx-item NgxCarouselItem *ngFor="let Question of Questions; let i = index">
      <mat-card style="background:{{getColor()}}">
        <h1>{{Question}}</h1>
      </mat-card>
    </ngx-item>
    <div layout="row" flex>
      <button NgxCarouselPrev class='leftRs'>&lt;</button>
      <button NgxCarouselNext class='rightRs'>&gt;</button>
    </div>
  </ngx-carousel>

How do I set background colors dynamically for Angular 5 Material objects?

Solution

I figured this out after some considerable effort…

<mat-card [style.background]=myColors[i]>

If you look carefully you will notice two things I learned: 1) any time you want to assign a variable value to an element, you have to wrap that element name in brackets, 2) there are many different (and sparsely documented) ways to name the same element such as style=”background: also being written as [style.background]= , one of which won’t handle variable values, but the other one will.

Answered By – AppDreamer

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.