import { Component , EventEmitter , Input , Output , ViewEncapsulation , forwardRef , ChangeDetectionStrategy , ChangeDetectorRef , ElementRef } from '@angular/core' ; import { ControlValueAccessor , NG_VALUE_ACCESSOR } from '@angular/forms' ; import { coerceBooleanProperty } from '@angular/cdk/coercion' ; import { CoerceNumberProperty } from '../../utils/coerce/coerce-number' ; const RADIO_VALUE_ACCESSOR = { provide : NG_VALUE_ACCESSOR , useExisting : forwardRef ( ( ) => RadioButtonComponent ) , multi : true } ; let nextId = 0 ; @ Component ( { exportAs : 'ngxRadiobutton' , selector : 'ngx-radiobutton' , templateUrl : './radiobutton.component.html' , styleUrls : [ './radiobutton.component.scss' ] , host : { class : 'ngx-radiobutton' , '[class.disabled]' : 'disabled' } , providers : [ RADIO_VALUE_ACCESSOR ] , encapsulation : ViewEncapsulation . None , changeDetection : ChangeDetectionStrategy . OnPush } ) export class RadioButtonComponent implements ControlValueAccessor { readonly UNIQUE_ID = `ngx-radio-${ ++ nextId }` ; @ Input ( ) id : string = this . UNIQUE_ID ; @ Input ( ) name : string = this . UNIQUE_ID ; @ Input ( ) radioId = `${ this . id }-radio` ; @ Input ( ) @ CoerceNumberProperty ( ) tabindex = 0 ; @ Input ( ) get checked ( ) { return this . _checked ; } set checked ( checked ) { checked = coerceBooleanProperty ( checked ) ; if ( this . _checked !== checked ) { this . _checked = checked ; this . onChangeCallback ( this . _value ) ; } this . cdr . detectChanges ( ) ; this . cdr . markForCheck ( ) ; } @ Input ( ) get value ( ) : any { return this . _value ; } set value ( value ) { if ( this . _value !== value ) { this . _value = value ; this . onChangeCallback ( this . _value ) ; } } @ Input ( ) get disabled ( ) { return this . _disabled || this . groupDisabled ; } set disabled ( disabled ) { this . _disabled = coerceBooleanProperty ( disabled ) ; } @ Output ( ) change = new EventEmitter < any > ( ) ; @ Output ( ) blur = new EventEmitter < Event > ( ) ; @ Output ( ) focus = new EventEmitter < FocusEvent > ( ) ; public groupDisabled = false ; public isInGroup = false ; private _checked = false ; private _value = false ; private _disabled = false ; constructor ( private readonly cdr , private readonly elementRef ) { } _onInputChange ( event ) { event . stopPropagation ( ) ; this . checked = true ; } writeValue ( value ) { this . value = value ; } onFocus ( e ) { this . focus . emit ( e ) ; this . onTouchedCallback ( ) ; } focusElement ( ) { this . elementRef . nativeElement . getElementsByClassName ( 'radio-label' ) [ 0 ] . focus ( ) ; } registerOnChange ( fn ) { this . onChangeCallback = fn ; } registerOnTouched ( fn ) { this . onTouchedCallback = fn ; } onSpace ( ev ) { ev . stopPropagation ( ) ; ev . preventDefault ( ) ; this . checked = true ; } private onChangeCallback ( value ) { if ( this . checked ) { this . change . emit ( value ) ; } } private onTouchedCallback ( ) { } }