Reputation: 61
I am trying to set the bg-color of MatChips dynamically when/if they get the selected property. I have a list of options available, which is the same for all users (represented by "chiplists" in app.component of the stackblitz sample) and and a list of the user-selected chips (i.e. "selected"). Both of these lists are dynamic in my app. What I have so far is:
<mat-chip #ref="matChip" [selected]="chip.value?.selected
[ngStyle]="ref.selected && {'background-color': chip.value.color}">
</mat-chip>
but it throws ExpressionChangedAfterItHasBeenCheckedError
for background-color: undefined
as initial state, which is expected?, I suppose.
Using [ngClass]
is a possible solution, pairing a custom css class with the .mat-chip-selected
class, but I can't be generating a bunch of hardcoded css classes, as the colours may change in the future.
The stackblitz link below showcases this behaviour, the error is logged in the console:
https://stackblitz.com/edit/angular-y5kfwc
https://stackblitz.com/edit/angular-anjuyf
Notice that while the stackblitz sample is working as intended, albeit with the error, my app doesn't colour the chips at all, whether selected or not.
Edit: My app's angular and material versions are the same as the package.json
in stackblitz sample.
Edit2: I did add a fork that better showcases what I am after. I am not looking to eliminate the error alone. I'm looking to add colours to the chips dynamically at render time.
Upvotes: 2
Views: 13116
Reputation: 425
simply call/use this class in mat-chip
.chip{
background-color: #3f51b5;
color: #fff;
}
Upvotes: 0
Reputation: 203
you may remove this line
[ngStyle]="ref.selected && {'background-color': 'black'}"
to change the color of the selected chip, target it using css.
on app.component.css
.my-chip .mat-chip-selected {
background-color: #000 !important;
color: #fff;
}
app.component.html
<mat-chip-list class="mat-chip-list-stacked my-chip" *ngFor="let list of lists | keyvalue" multiple>
<mat-chip #ref="matChip"
*ngFor="let chip of list.value | keyvalue"
(click)="toggle(ref)"
color="primary"
[selected]="chip.value.selected">
{{chip.value.de}}
</mat-chip>
</mat-chip-list>
I added a class to mat chip list named my-chip to identity it and target the sub element below which is .mat-chip-selected.
hope it solve your problem
Cheers!
Upvotes: 3