import { Directive , Input , HostListener , ElementRef , Renderer2 , OnInit , OnDestroy } from '@angular/core' ; import { Subscription } from 'rxjs' ; import { NglPick } from './pick' ; @ Directive ( { selector : '[nglPickOption]' , exportAs : 'nglPickOption' , host : { 'role' : 'button' , } , } ) export class NglPickOption implements OnInit , OnDestroy { get active ( ) { return this . _active ; } @ Input ( 'nglPickOption' ) set setValue ( value ) { this . _value = value ; } @ Input ( ) nglPickActiveClass : string ; private _value : any ; private _active = false ; private _subscription : Subscription ; constructor ( private element , private renderer , private nglPick ) { } @ HostListener ( 'click' ) @ HostListener ( 'keydown.Space' , [ '$event' ] ) @ HostListener ( 'keydown.Enter' , [ '$event' ] ) pick ( evt ? ) { if ( evt ) { evt . preventDefault ( ) ; } this . nglPick . selectOption ( this . _value ) ; } ngOnInit ( ) { this . _subscription = this . nglPick . values . subscribe ( value => { this . _active = this . _isActive ( value ) ; const activeClass = this . nglPickActiveClass || this . nglPick . nglPickActiveClass ; if ( activeClass ) { if ( this . active ) { this . renderer . addClass ( this . element . nativeElement , activeClass ) ; } else { this . renderer . removeClass ( this . element . nativeElement , activeClass ) ; } } } ) ; } ngOnDestroy ( ) { this . _subscription . unsubscribe ( ) ; this . nglPick . optionRemoved ( this . _value ) ; } private _isActive ( value ) { if ( this . nglPick . isMultiple ) { if ( ! value ) { return false ; } return Array . isArray ( value ) ? value . indexOf ( this . _value ) > - 1 : ! ! value [ this . _value ] ; } else { return this . _value === value ; } } }