When we "Tab" into a input field, we want to select all the content, if we start typing, it should remove the existing content and add new content.

We can use HMTL 'select' event.

  @HostListener('select', ['$event'])
onSelect($event: UIEvent) {
this.fullFieldSelected = this.input.selectionStart ===
&& this.input.selectionEnd === this.input.value.length;
}

'fullFieldSelected' variable check whether the field is selected.

If we start typing, it should clean the input value and move the cursor to the first placeholder place.

    // Select the whole field
if (this.fullFieldSelected) {
this.input.value = this.buildPlaceHolder();
const firstPlaceHolderPos = findIndex(this.input.value, (char) => char === '_');
this.input.setSelectionRange(firstPlaceHolderPos, firstPlaceHolderPos);
}

There is one problem, if using trying to do Ctrl + C, it will clean up the field and put 'c' there. So we should prevent this happen.

  @HostListener('keydown', ['$event', '$event.keyCode'])
onKeyDown($event: KeyboardEvent, keyCode) { // if user trying to do copy & paste, then we don't want to
// overwrite the value
if ($event.metaKey || $event.ctrlKey) {
return;
} if(keyCode !== TAB) {
$event.preventDefault();
} // get value for the key
const val = String.fromCharCode(keyCode);
// get position
const cursorPos = this.input.selectionStart; // Select the whole field
if (this.fullFieldSelected) {
this.input.value = this.buildPlaceHolder();
const firstPlaceHolderPos = findIndex(this.input.value, (char) => char === '_');
this.input.setSelectionRange(firstPlaceHolderPos, firstPlaceHolderPos);
} switch(keyCode) {
case LEFT_ARROW:
this.handleLeftArrow(cursorPos);
return;
case RIGHT_ARROW:
this.handleRightArrow(cursorPos);
return;
case BACKSPACE:
this.handleBackSpace(cursorPos);
return;
case DELETE:
this.handleDelete(cursorPos);
return;
} const maskDigit = this.mask.charAt(cursorPos);
const digitValidator = digitValidators[maskDigit] || neverValidator;
if (digitValidator(val)) {
overWriteCharAtPosition(this.input, val, cursorPos);
this.handleRightArrow(cursorPos);
}
}

So, we check whether '$event.metaKey or $event.ctrlKey', if those keys are pressed, then we consider user is trying to copy & paste.

--------

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

import * as includes from 'lodash.includes';
import * as findLastIndex from 'lodash.findlastindex';
import * as findIndex from 'lodash.findIndex';
import {SPECIAL_CHARACTERS, TAB, overWriteCharAtPosition, LEFT_ARROW, RIGHT_ARROW, BACKSPACE, DELETE} from './mask.utils';
import {digitValidators, neverValidator} from './digit_validation'; @Directive({
selector: '[au-mask]'
})
export class AuMaskDirective implements OnInit { @Input('au-mask') mask = ''; input: HTMLInputElement;
fullFieldSelected = false; ngOnInit() {
this.input.value = this.buildPlaceHolder();
} constructor(el: ElementRef) {
this.input = el.nativeElement;
} @HostListener('select', ['$event'])
onSelect($event: UIEvent) {
this.fullFieldSelected = this.input.selectionStart ===
&& this.input.selectionEnd === this.input.value.length;
} @HostListener('keydown', ['$event', '$event.keyCode'])
onKeyDown($event: KeyboardEvent, keyCode) { // if user trying to do copy & paste, then we don't want to
// overwrite the value
if ($event.metaKey || $event.ctrlKey) {
return;
} if(keyCode !== TAB) {
$event.preventDefault();
} // get value for the key
const val = String.fromCharCode(keyCode);
// get position
const cursorPos = this.input.selectionStart; // Select the whole field
if (this.fullFieldSelected) {
this.input.value = this.buildPlaceHolder();
const firstPlaceHolderPos = findIndex(this.input.value, (char) => char === '_');
this.input.setSelectionRange(firstPlaceHolderPos, firstPlaceHolderPos);
} switch(keyCode) {
case LEFT_ARROW:
this.handleLeftArrow(cursorPos);
return;
case RIGHT_ARROW:
this.handleRightArrow(cursorPos);
return;
case BACKSPACE:
this.handleBackSpace(cursorPos);
return;
case DELETE:
this.handleDelete(cursorPos);
return;
} const maskDigit = this.mask.charAt(cursorPos);
const digitValidator = digitValidators[maskDigit] || neverValidator;
if (digitValidator(val)) {
overWriteCharAtPosition(this.input, val, cursorPos);
this.handleRightArrow(cursorPos);
}
} handleDelete(cursorPos) {
overWriteCharAtPosition(this.input, '_', cursorPos);
this.input.setSelectionRange(cursorPos, cursorPos);
} handleBackSpace(cursorPos) {
const previousPos = this.calculatePreviousCursorPos(cursorPos);
if (previousPos > -) {
overWriteCharAtPosition(this.input, '_', previousPos);
this.input.setSelectionRange(previousPos, previousPos);
}
} calculateNextCursorPos(cursorPos) {
const valueBeforeCursor = this.input.value.slice(cursorPos + );
const nextPos = findIndex(valueBeforeCursor, (char) => !includes(SPECIAL_CHARACTERS, char));
return nextPos;
} calculatePreviousCursorPos(cursorPos) {
const valueBeforeCursor = this.input.value.slice(, cursorPos);
const previousPos = findLastIndex(valueBeforeCursor, (char) => !includes(SPECIAL_CHARACTERS, char));
return previousPos;
} handleRightArrow(cursorPos) {
const nextPos = this.calculateNextCursorPos(cursorPos);
if(nextPos > -) {
const newNextPos = cursorPos + nextPos + ;
this.input.setSelectionRange(newNextPos, newNextPos);
}
} handleLeftArrow(cursorPos) {
const previousPos = this.calculatePreviousCursorPos(cursorPos);
if(previousPos > -) {
this.input.setSelectionRange(previousPos, previousPos);
}
} buildPlaceHolder(): string {
const chars = this.mask.split(''); const value = chars.reduce((acc, curr) => {
return acc += includes(SPECIAL_CHARACTERS, curr) ?
curr :
'_';
}, ''); return value;
} }

[Angular] The Select DOM Event and Enabling Text Copy的更多相关文章

  1. 节点操作,节点属性的操作及DOM event事件

    ##1. 节点操作 createElement(标签名) 创建一个指定名称的元素 someone.appendChild(new_node) 追加一个子节点(作为最后的子节点) someone.ins ...

  2. [DOM Event Learning] Section 1 DOM Event 处理器绑定的几种方法

    [DOM Event Learning] Section 1 DOM Event处理器绑定的几种方法   网页中经常需要处理各种事件,通常的做法是绑定listener对事件进行监听,当事件发生后进行一 ...

  3. Angular this vs $scope $event事件系统

    this vs $scope ------------------------------------------------------------------------------ 'this' ...

  4. JavaScript 基础(四) - HTML DOM Event

    HTML DOM Event(事件) HTML 4.0 的新特性之一是有能力使 HTML 事件触发浏览器中的动作(action),比如当用户点击某个 HTML 元素时启动一段 JavaScript.下 ...

  5. [DOM Event Learning] Section 4 事件分发和DOM事件流

    [DOM Event Learning] Section 4 事件分发和DOM事件流 事件分发机制: event dispatch mechanism. 事件流(event flow)描述了事件对象在 ...

  6. [DOM Event Learning] Section 3 jQuery事件处理基础 on(), off()和one()方法使用

    [DOM Event Learning] Section 3 jQuery事件处理基础 on(),off()和one()方法使用   jQuery提供了简单的方法来向选择器(对应页面上的元素)绑定事件 ...

  7. [DOM Event Learning] Section 2 概念梳理 什么是事件 DOM Event

    [DOM Event Learning] Section 2 概念梳理 什么是事件 DOM Event   事件 事件(Event)是用来通知代码,一些有趣的事情发生了. 每一个Event都会被一个E ...

  8. HTML DOM Event对象

    我们通常把HTML DOM Event对象叫做Event事件 事件驱动模型 事件源:(触发事件的元素)事件源对象是指event对象 其封装了与事件相关的详细信息. 当事件发生时,只能在事件函数内部访问 ...

  9. [ReactJS] DOM Event Listeners in a React Component

    React doesn't provide the listener to listen the DOM event. But we can do it in React life cycle: So ...

随机推荐

  1. [Python] Understand Mutable vs. Immutable objects in Python

    In this lesson, you will learn what mutable and immutable objects are, and the difference between th ...

  2. uva103 - Stacking Boxes(DAG)

    题目:uva103 - Stacking Boxes(DAG) 题目大意:给出N个boxes, 而且给出这些箱子的维度.要求找一个最长的序列.可以使得以下的箱子一定可以有个维度序列大于上面的那个箱子的 ...

  3. 值得学习的CSS知识

    这里零度给大家推荐几个值得学习的CSS技巧,能让你编写网页事半功倍!一.清除默认值 通常 padding 的默认值为 0,background-color 的默认值是 transparent.但是在不 ...

  4. uva 11248 最小割

    Dinic 1 #include<iostream> #include<string> #include<algorithm> #include<cstdli ...

  5. API集合开发文档

    百度翻译api https://www.cnblogs.com/DevilX5/p/7079470.html 实现QQ第三方登录.网站接入 http://blog.csdn.net/u01067894 ...

  6. Autoencoders and Sparsity(一)

    An autoencoder neural network is an unsupervised learning algorithm that applies backpropagation, se ...

  7. HDU 1716 排列2

    排列2 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...

  8. absolute、relative,toggle()

    測试代码例如以下: <div> <div class="global">不应用样式</div> <div class="glob ...

  9. js---BOM 的理解方法

    windows 方法 window.close(); //关闭窗口   window.alert("message"); //弹出一个具有OK按钮的系统消息框,显示指定的文本   ...

  10. js--递归详解

    1 函数的调用 eg1:阶乘算法 var f = function (x) { if (x === 1) { return 1; } else { return x * f(x - 1); } }; ...