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(' ');
}

最新文章

  1. WHMCS成功安装和使用方法及添加支付宝,PayPal收款教程
  2. Moon.Orm 5.0(MQL版)及之前版本的开源计划
  3. JavaScript DOM学习总结(一)
  4. ThinkPHP中getField( )和field( )
  5. 【转】Tomcat中部署java web应用程序
  6. Masonry 固定宽度 等间距
  7. 获取scrollTop兼容各浏览器的方法,以及body和documentElement
  8. Coreseek:索引和检测的第二步骤施工
  9. 每天一个Linux命令(11)--nl命令
  10. WPF 自定义RadioButton样式
  11. javascript 正则表达式补充
  12. UOJ236 IOI2016 Railroad 差分、欧拉回路、最小生成树
  13. Oracle 存储过程或函数传入的数值参数number
  14. 阿里云服务器搭建FTP
  15. Django MTV模式详解
  16. 2017广东工业大学程序设计竞赛决赛 Problem E: 倒水(Water) (详解)
  17. LOJ121 【离线可过】动态图连通性
  18. Vue学习笔记:编译过程
  19. Vuex-Action
  20. Mac上Homebrew的使用——Homebrew 使 OS X 更完整

热门文章

  1. 【Codeforces Round #452 (Div. 2) D】Shovel Sale
  2. 课程与教学管理系统(CMS):Sakai
  3. [appium]-9宫格解锁方法
  4. 详解javascript的深拷贝与浅拷贝
  5. Visual C# 2008 调试技巧
  6. UML学习总结(3)——StarUML指导手册
  7. Maven报错Missing artifact jdk.tools:jdk.tools:jar:1.7--转
  8. [Node] Run Any Version of a Node Tool with npx
  9. js实现类似页面广告一段时间自动打开一段时间自动关闭的功能
  10. [Angular2] @Ngrx/store and @Ngrx/effects learning note