import { isPlatformBrowser } from '@angular/common' ; import { Directive , ElementRef , Input , OnInit , OnDestroy , OnChanges , SimpleChanges , Optional , Inject , PLATFORM_ID } from '@angular/core' ; import { create as createLadda , LaddaButton } from 'ladda' ; import { LaddaConfig , LaddaConfigArgs , configAttributes } from './ladda-config' ; export type LaddaValue = boolean | number | undefined | null ; @ Directive ( { selector : '[ladda]' , } ) export class LaddaDirective implements OnInit , OnDestroy , OnChanges { private el : HTMLButtonElement ; private ladda : LaddaButton | undefined = undefined ; @ Input ( 'ladda' ) loading : LaddaValue ; @ Input ( ) disabled = false ; constructor ( el , @ Inject ( LaddaConfig ) @ Optional ( ) config , @ Inject ( PLATFORM_ID ) private platformId ) { this . el = el . nativeElement ; if ( ! config ) { return ; } for ( let attribute in configAttributes ) { let configValue = config [ configAttributes [ attribute ] ] ; if ( ! configValue ) { continue ; } if ( ! this . el . getAttribute ( attribute ) ) { let value = ( typeof configValue === "number" ) ? configValue . toString ( ) : configValue ; this . el . setAttribute ( attribute , value ) ; } } } ngOnChanges ( changes ) { if ( ! this . ladda ) { return ; } if ( changes . loading ) { this . updateLadda ( changes . loading . previousValue ) ; } if ( changes . disabled ) { this . updateDisabled ( ) ; } } ngOnInit ( ) { if ( ! isPlatformBrowser ( this . platformId ) ) { return ; } this . ladda = createLadda ( this . el ) ; setTimeout ( ( ) => { this . updateLadda ( false ) ; } , 0 ) ; } ngOnDestroy ( ) { if ( this . ladda ) { this . ladda . remove ( ) ; } } private updateLadda ( previousValue ) { if ( ! this . ladda ) { return ; } let loading = typeof this . loading === 'number' || ! ! this . loading ; let wasLoading = typeof previousValue === 'number' || ! ! previousValue ; if ( ! loading ) { if ( wasLoading ) { this . ladda . stop ( ) ; } return this . updateDisabled ( ) ; } if ( ! wasLoading ) { this . ladda . start ( ) ; } if ( typeof this . loading === 'number' ) { this . ladda . setProgress ( this . loading ) ; } } private updateDisabled ( ) { this . el . disabled = this . disabled ; } }