Custom checkbox input component styled with Switchery

I’m trying to create a custom checkbox component styled with Switchery that can be used in a form like any other <input type="checkbox" ... /> component.

The code I have now takes care of the styling:

import {Component,ViewChild,AfterViewInit,Input} from 'angular2/core';
import switchery from 'switchery';

@Component({
  selector: 'switchery-checkbox',
  template: `<input #checkbox type="checkbox" class="js-switch"/>`,
})
export class SwitcheryComponent implements AfterViewInit {
  @Input() options: Switchery.Options = {};
  @ViewChild('checkbox') checkbox: any;
  ngAfterViewInit() {
    new switchery(this.checkbox.nativeElement,
                  this.options);
  }
}

What do I have to add to be able to use it in a template like in the following code? It should ideally implement all the functionality of <input type="checkbox" />.

<switchery-checkbox
     [(ngModel)]="model.onOrOff"
     ngControl="onOrOff"
     [disabled]="disabledCondition"
     ... >
</switchery-checkbox>

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

In fact you need to make your component “ngModel-compliant” but implementing a custom value accessor. Here is the way to do: @Component({ selector: 'switchery-checkbox', template: ` <input #checkbox type="checkbox" (change)="onChange($event.target.checked)" class="js-switch"/> `, (...) }) export class SwitcheryComponent implements AfterViewInit, ControlValueAccessor { @Input() options: Switchery.Options = {}; @Input() disabled:boolean = false; @ViewChild('checkbox') checkbox: any; value: boolean = false; onChange = (_) => {}; onTouched = () => {}; writeValue(value: any): void { this.value = value; this.setValue(this.value); } registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } registerOnTouched(fn: () => void): void { this.onTouched = fn; } ngAfterViewInit() { this.switcher… Read more »