import { Component , Input , Output , EventEmitter , OnInit , forwardRef , ElementRef , ViewChild , OnChanges , SimpleChanges , ChangeDetectorRef , ChangeDetectionStrategy } from '@angular/core' ; import { ControlValueAccessor , NG_VALUE_ACCESSOR } from '@angular/forms' ; import { helpers } from 'ngx-tethys/util' ; @ Component ( { selector : 'thy-switch' , templateUrl : './switch.component.html' , changeDetection : ChangeDetectionStrategy . OnPush , providers : [ { provide : NG_VALUE_ACCESSOR , useExisting : forwardRef ( ( ) => ThySwitchComponent ) , multi : true } ] } ) export class ThySwitchComponent implements OnInit , ControlValueAccessor , OnChanges { public model : boolean ; public type ? : String = 'primary' ; public size ? : String = '' ; public disabled ? : Boolean = false ; public classNames : string [ ] ; public typeArray : string [ ] = [ 'primary' , 'info' , 'warning' , 'danger' ] ; public sizeArray : string [ ] = [ 'lg' , '' , 'sm' ] ; private initialized = false ; @ ViewChild ( 'switch' , { static : true } ) switchElementRef : ElementRef ; /**
     * 类型，目前分为: 'primary' |'info' | 'warning' | 'danger'
     */ @ Input ( ) set thyType ( value ) { if ( ! this . typeArray . includes ( value ) ) { value = 'primary' ; } this . type = value ; if ( this . initialized ) { this . setClassNames ( ) ; } } default @ Input ( ) set thySize ( value ) { if ( ! this . sizeArray . includes ( value ) ) { value = '' ; } this . size = value ; if ( this . initialized ) { this . setClassNames ( ) ; } } default @ Input ( ) thyDisabled : boolean = false ; deprecated @ Output ( ) thyChange : EventEmitter < Event > = new EventEmitter < Event > ( ) ; constructor ( public cdr ) { } ngOnInit ( ) { this . setClassNames ( ) ; this . initialized = true ; } ngOnChanges ( changes ) { if ( changes . thyDisabled ) { const value = changes . thyDisabled . currentValue ; this . disabled = helpers . isBoolean ( value ) ? Boolean ( value ) : value === 'true' || value === '1' ; this . setClassNames ( ) ; } } public onModelChange : Function = ( ) => { } ; public onModelTouched : Function = ( ) => { } ; writeValue ( value ) { this . model = value ; this . cdr . markForCheck ( ) ; } registerOnChange ( fn ) { this . onModelChange = fn ; } registerOnTouched ( fn ) { this . onModelTouched = fn ; } setDisabledState ( isDisabled ) { this . disabled = isDisabled ; this . setClassNames ( ) ; } toggle ( event ) { this . model = ! this . model ; this . onModelChange ( this . model ) ; this . thyChange . emit ( event ) ; } setClassNames ( ) { this . classNames = [ `thy-switch-${ this . type }` ] ; if ( this . size ) { this . classNames . push ( `thy-switch-${ this . size }` ) ; } if ( this . disabled ) { this . classNames . push ( `thy-switch-disabled` ) ; if ( this . model ) { this . classNames . push ( `thy-switch-disabled-true` ) ; } } } }