In: Computer Science
Use attribute directives to display credit card logo based on the credit card number Use simplified rules as follows:
4 visa
5 mastercard
34 and 37 amex
30, 36, 38, 39 diners
60, 64, 65 discover
import {Directive, Input, OnChanges, HostBinding} from '@angular/core';
enum CardType { VISA = 'visa', MASTERCARD = 'mastercard', AMERICAN_EXPRESS = 'american-express', DINERS = 'diners', DISCOVER = 'discover' UNKNOWN = 'unknown'}
@Directive({
selector: '[ccLogo]'
})
export class CreditCardImageDirective implements OnChanges {
@HostBinding('src')
imageSource;
@Input()
cardNumber: string
ngOnChanges() {
this.imageSource = 'assets/card-types/' + this.getCardTypeFromNumber() + '.png';
}
getCardTypeFromNumber(): CardType {
if (this.cardNumber) {
if (this.cardNumber.startsWith('37') || this.cardNumber.startsWith('34')) {
return CardType.AMERICAN_EXPRESS;
} else if (this.cardNumber.startsWith('4')) {
return CardType.VISA;
} else if (this.cardNumber.startsWith('5')) {
return CardType.MASTERCARD;
} else if (this.cardNumber.startsWith('30') || this.cardNumber.startsWith('36') || this.cardNumber.startsWith('38') || this.cardNumber.startsWith('39')) {
return CardType.DINERS;
} else if (this.cardNumber.startsWith('60') || this.cardNumber.startsWith('64') || this.cardNumber.startsWith('65')) {
return CardType.DISCOVER;
}
}
return CardType.UNKNOWN;
}
}