import { Component , AfterViewInit , OnDestroy , ViewChild , ElementRef , ChangeDetectorRef , Input , Output , EventEmitter } from '@angular/core' ; import { NgForm } from '@angular/forms' ; import { PaymentService } from '../payment.service' ; import { Charge , Source } from '../models' ; @ Component ( { selector : 'payment-form' , templateUrl : './payment-form.component.html' , styleUrls : [ './payment-form.component.sass' ] } ) export class PaymentFormComponent implements AfterViewInit , OnDestroy { @ Input ( ) totalAmount : number ; @ Output ( ) stripeResult = new EventEmitter < Charge | Source > ( ) ; result : Charge | Source ; @ ViewChild ( 'cardElement' ) cardElement : ElementRef ; card : any ; formError : string ; formComplete = false ; loading = false ; constructor ( private cd , public pmt ) { } ngAfterViewInit ( ) { this . card = this . pmt . elements . create ( 'card' ) ; this . card . mount ( this . cardElement . nativeElement ) ; this . card . on ( 'change' , ( evt ) => { this . formError = evt . error ? evt . error . message : null ; this . formComplete = evt . complete ; this . cd . detectChanges ( ) ; } ) ; } formHandler ( ) { this . loading = true ; let action ; if ( this . totalAmount ) { action = this . pmt . createCharge ( this . card , this . totalAmount ) ; } else { action = this . pmt . attachSource ( this . card ) ; } action . subscribe ( data => { this . result = data ; this . stripeResult . emit ( data ) ; this . loading = false ; } , err => { this . result = err ; this . loading = false ; } ) ; } ngOnDestroy ( ) { this . card . destroy ( ) ; } }