Search code examples
angularjsvmware-clarity

clr-checkbox dynamic set of checkboxes with different colors AngularJs


I am following the https://vmware.github.io/clarity/documentation/v0.13/checkboxes and need to use different colors when the checkbox is checked.

Code HTML:

<div class="form-group">
  <label>With a list of objects</label>
  <clr-checkbox *ngFor="let item of items$"
                    [(clrChecked)]="item.running"
                    [clrDisabled]="item.disabled">
                    {{ item.name }}
                </clr-checkbox>

</div>

Code Controller:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-checkboxgroup',
  templateUrl: './checkboxgroup.component.html',
  styleUrls: ['./checkboxgroup.component.scss']
})
export class CheckboxgroupComponent implements OnInit {

  items$: Object;
  constructor() { }

  ngOnInit() {
    this.items$ = [{id:1,name:'Custom',color:'cyan'},
  {id:2,name:'Primary',color:'green',running:false,disabled:false},
{id:3,name:'Info',color:'blue',running:false,disabled:false},
{id:4,name:'Warning',color:'yellow',running:false,disabled:false},
{id:5,name:'Danger',color:'red',running:false,disabled:false}];
  }

}

Solution

  • You can achieve that with the help of the currentColor keyword in CSS and a slight change of the default Clarity checkbox template. The template would look as follows:

    <clr-checkbox *ngFor="let item of items$" [style.color]="item.color" [(clrChecked)]="item.running" [clrDisabled]="item.disabled">
            <span class="checkbox-label">{{ item.name }}</span>
    </clr-checkbox>
    

    Then apply the following CSS in your component CSS.

    .checkbox-label {
       color: #000;
    }
    
    clr-checkbox ::ng-deep input[type=checkbox]:checked+label::before {
       background-color: currentColor;
    }
    

    You can see that I used style binding on the clr-checkbox's color property. Hence, the color of a checked checkbox will inherit that color through currentColor.

    Btw, if you add the above CSS snippet in your global style file instead of a component style, you don't need that ::ng-deep.

    Here is the working sample:

    https://stackblitz.com/edit/clr-checkbox-checkbox-multi-color