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. Android Multiple dex files define BuildConfig

    dexOptions { preDexLibraries = false }

  2. 给已有数据的oracle表建立外键关系

    PS:这里是给自己做个备忘,下次遇到同类问题的时候,方便查找: 客户在有主外键关系的2张表进行页面删除时报错已有子记录,运维后台处理的时候应该找出相应的数据,先删除子记录,在删主表记录:但客户要的急, ...

  3. SpringMVC响应Ajax请求(@Responsebody注解返回页面)

    项目需求描述:page1中的ajax请求Controller,Controller负责将service返回的数据填充到page2中,并将page2整个页面返回到page1中ajax的回调函数. 一句话 ...

  4. springboot入门(三)-- springboot集成mybatis及mybatis generator工具使用

    前言 mybatis是一个半自动化的orm框架,所谓半自动化就是mybaitis只支持数据库查出的数据映射到pojo类上,而实体到数据库的映射需要自己编写sql语句实现,相较于hibernate这种完 ...

  5. 5W1H分析法和5W2H分析法

    5W1H分析法也称六何分析法,是一种思考方法,也可以说是一种创造技法.是对选定的项目.工序或操作,都要从原因(WHY).对象(WHAT).地点(WHERE).时间(WHEN).人员(WHO).方法(H ...

  6. IOS获取手机设备所有应用

    //返回一个数组 1 NSMutableArray *applist = [[NSMutableArray alloc]init]; NSString *pathOfApplications = @& ...

  7. 打开utf-8文件乱码的解决方法

    gvim一直用的好好的,但是今天看一网友贴出来的代码时,却发现中文显示乱码了.... 使用notepad++打开,右下角显示是utf-8 w/0 BOM. 马上放狗, 发现解决方法如下:   在_vi ...

  8. cocos2d-x 一些实用的函数

    1.  自己主动释放粒子内存的函数      setAutoRemoveOnFinish(bool var) 2. 解决使用tiled出现像素线的问题在代码中搜索"CC_FIX_ARTIFA ...

  9. C语言深度剖析-----函数与指针的分析

                          指针的本质 指针需要保证指向任意数据类型,所以指针变量都占用32位bit即4字节. PS:不同机器上,指针占用内存不一                   ...

  10. [arm]虚拟机,2440开发板,主机三者互通

    想实现3着互通先必须保证三者的网段是相同的: 首先查看电脑主机的IP: 然后再看看虚拟机的IP: 惊喜的发现,他们在一个网段上---那就不用改了-- 再去看看开发板上的IP: 这里注意,输入命令时,是 ...