We will use 'HostListener' and 'HostBinding' to accomplish the task.

The HTML:

      <label>
Credit Card Number
<input
name="credit-card"
type="text"
credit-card
placeholder="Enter your 16-digit card number">
</label>

Create directive:

import { Directive, ElementRef, HostListener, HostBinding } from '@angular/core';

@Directive({
selector: '[credit-card]'
})
export class CreditCardDirective {
constructor(private element: ElementRef) {}
}

Add a HostListener when user type input:

And we want that the max length of string user type is 16 and it should be formatted as '6666 6666 6666 6666'.

  @HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
this.border = "";
const input = event.target as HTMLInputElement; // the length should be no more than 16
let trimmed = input.value.replace(/\s+/g, '');
if(trimmed.length > 16) {
trimmed = trimmed.substr(0, 16);
} // should be 6666 6666 6666 6666
let numbers = [];
for(let i = 0; i < trimmed.length; i +=4) {
numbers.push(trimmed.substr(i, 4));
} input.value = numbers.join(' ');
}

Now we want to use @HostBinding to change style props when what user entered is not a number:

  onKeyDown(event: KeyboardEvent) {
this.border = "";
const input = event.target as HTMLInputElement; // the length should be no more than 16
let trimmed = input.value.replace(/\s+/g, '');
if(trimmed.length > 16) {
trimmed = trimmed.substr(0, 16);
} // if we pass in char, show red border
if((/[^\d]/g).test(trimmed)) {
this.border = '1px solid red';
} // should be 6666 6666 6666 6666
let numbers = [];
for(let i = 0; i < trimmed.length; i +=4) {
numbers.push(trimmed.substr(i, 4));
} input.value = numbers.join(' ');
}

[Angular] Using directive to create a simple Credit card validator的更多相关文章

  1. [Angular] Create a simple *ngFor

    In this post, we are going to create our own structure directive *ngFor. What it should looks like i ...

  2. [Angular] Custom directive Form validator

    Create a directive to check no special characters allowed: import {Directive, forwardRef} from '@ang ...

  3. [Angular] Export directive functionalities by using 'exportAs'

    Directive ables to change component behaives and lookings. Directive can also export some APIs which ...

  4. [Angular 2] Directive intro and exportAs

    First, What is directive, what is the difference between component and directive. For my understandi ...

  5. 关于angular 自定义directive

    关于angular 自定义directive的小结 首先我们创建一个名为"expander"的自定义directive指令: angular.module("myApp& ...

  6. Create a simple REST web service with Python--转载

    今日尝试用python建立一个restful服务. 原文地址:http://www.dreamsyssoft.com/python-scripting-tutorial/create-simple-r ...

  7. [Angular] Test Directive

    directive: import { Directive, HostListener, HostBinding, ElementRef } from '@angular/core'; @Direct ...

  8. Real Time Credit Card Fraud Detection with Apache Spark and Event Streaming

    https://mapr.com/blog/real-time-credit-card-fraud-detection-apache-spark-and-event-streaming/ Editor ...

  9. Create a Bootable MicroSD Card

    http://gumstix.org/create-a-bootable-microsd-card.html Create a Bootable MicroSD Card Beginners Note ...

随机推荐

  1. [Vue + TS] Using Route events inside Vue

    vue-router introduces new hooks into the component. In this lesson we’ll show you how to use these n ...

  2. ED/EP系列1《简单介绍》

    电子存折(ED:ElectronicDeposit)一种为持卡人进行消费.取现等交易而设计的支持个人识别码(PIN)保护的金融IC卡应用. 它支持圈存.圈提.消费和取现等交易. 电子钱包(EP:Ele ...

  3. LocationOnScreen-控件在手机屏幕中的位置坐标

    我们可以通过如下的方法获得某个控件在屏幕中的绝对坐标 代码如下: private int[] mHistoryDisplayButtonLocation; private int mHistoryDi ...

  4. Hypervisor, computer system, and virtual processor scheduling method

    A hypervisor calculates the total number of processor cycles (the number of processor cycles of one ...

  5. (转)如何启动或关闭数据库的归档(ARCHIVELOG)模式

    转自:http://www.eygle.com/archives/2004/10/oracle_howtoeci.html Oracle数据库可以运行在2种模式下:归档模式(archivelog)和非 ...

  6. (转)linux的一个find命令配合rm删除某天前的文件

    转自:http://www.cnblogs.com/mingforyou/p/3930624.html 语句写法:find 对应目录 -mtime +天数 -name "文件名"  ...

  7. Flask项目之手机端租房网站的实战开发(二)

    说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家! 接着上一篇博客继续往下写 :https://blog.csdn.net/qq_41782425/article/details/8 ...

  8. ab压测返回结果解析

    Server Software:        Apache/2.2.25 (服务器软件名称及版本信息)Server Hostname:        localhost (服务器主机名)Server ...

  9. error app/styles/components/iconfont.scss (Line 12: Invalid GBK character "\xE5")

    因为要用到iconfont,引入iconfont到sass文件后,出现编译sass文件错误,如下截图: 解决方法:在顶部设置编码格式 @charset "utf-8"; 编译成功!

  10. VMware linux虚拟机在线识别新添加磁盘

    登录进虚拟机linux系统中执行以下命令,识别新增加的硬盘 echo "- - -" > /sys/class/scsi_host/host0/scan # ls /sys/ ...