projects/rebirth-ng/src/lib/switch/switch.component.ts
changeDetection | ChangeDetectionStrategy.OnPush |
providers |
{
: , : (() => ), : true
}
|
selector | re-switch |
styleUrls | switch.component.scss |
templateUrl | ./switch.component.html |
Properties |
Methods |
Inputs |
constructor(rebirthNGConfig: RebirthNGConfig, changeDetectorRef: ChangeDetectorRef)
|
|||||||||
Parameters :
|
cssClass
|
Type: |
disabled
|
Type: |
offText
|
Type: |
onText
|
Type: |
size
|
Type: |
type
|
Type: |
registerOnChange | ||||||
registerOnChange(fn: any)
|
||||||
Parameters :
Returns :
void
|
registerOnTouched | ||||||
registerOnTouched(fn: any)
|
||||||
Parameters :
Returns :
void
|
setDisabledState | ||||||
setDisabledState(isDisabled: boolean)
|
||||||
Parameters :
Returns :
void
|
toggle |
toggle()
|
Returns :
void
|
writeValue | ||||||
writeValue(obj: any)
|
||||||
Parameters :
Returns :
void
|
checked |
checked:
|
Type : boolean
|
Private onChange |
onChange:
|
Default value : (_: any) => null
|
Private onTouched |
onTouched:
|
Default value : () => null
|
import { Component, Input, ChangeDetectionStrategy, forwardRef, ChangeDetectorRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { RebirthNGConfig } from '../rebirth-ng.config';
@Component({
selector: 're-switch',
templateUrl: './switch.component.html',
styleUrls: ['./switch.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SwitchComponent),
multi: true
}]
})
export class SwitchComponent implements ControlValueAccessor {
@Input() type: 'default' | 'primary' | 'success' | 'info' | 'warning' | 'danger';
@Input() size: 'lg' | 'sm' | 'xs';
@Input() disabled: boolean;
@Input() onText: string;
@Input() offText: string;
@Input() cssClass: string;
checked: boolean;
private onChange = (_: any) => null;
private onTouched = () => null;
constructor(rebirthNGConfig: RebirthNGConfig, private changeDetectorRef: ChangeDetectorRef) {
this.onText = rebirthNGConfig.switchBtn.onText;
this.offText = rebirthNGConfig.switchBtn.offText;
this.type = <any>rebirthNGConfig.switchBtn.type;
}
toggle() {
if (this.disabled) {
return;
}
this.onTouched();
this.checked = !this.checked;
this.onChange(this.checked);
}
writeValue(obj: any): void {
this.checked = obj;
this.changeDetectorRef.markForCheck();
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
}
<div class="switch {{cssClass}} {{size ? 'btn-' + size : ''}}" (click)="toggle()" [ngClass]="{'disabled': disabled}">
<span class="switch-left {{checked ? 'bg-'+ type + ' active' : ''}}">
{{onText}}
</span><span class="switch-right {{!checked ? 'bg-'+ type + ' active' : ''}}">
{{offText}}
</span>
</div>