[Angular] The Select DOM Event and Enabling Text Copy
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的更多相关文章
- 节点操作,节点属性的操作及DOM event事件
##1. 节点操作 createElement(标签名) 创建一个指定名称的元素 someone.appendChild(new_node) 追加一个子节点(作为最后的子节点) someone.ins ...
- [DOM Event Learning] Section 1 DOM Event 处理器绑定的几种方法
[DOM Event Learning] Section 1 DOM Event处理器绑定的几种方法 网页中经常需要处理各种事件,通常的做法是绑定listener对事件进行监听,当事件发生后进行一 ...
- Angular this vs $scope $event事件系统
this vs $scope ------------------------------------------------------------------------------ 'this' ...
- JavaScript 基础(四) - HTML DOM Event
HTML DOM Event(事件) HTML 4.0 的新特性之一是有能力使 HTML 事件触发浏览器中的动作(action),比如当用户点击某个 HTML 元素时启动一段 JavaScript.下 ...
- [DOM Event Learning] Section 4 事件分发和DOM事件流
[DOM Event Learning] Section 4 事件分发和DOM事件流 事件分发机制: event dispatch mechanism. 事件流(event flow)描述了事件对象在 ...
- [DOM Event Learning] Section 3 jQuery事件处理基础 on(), off()和one()方法使用
[DOM Event Learning] Section 3 jQuery事件处理基础 on(),off()和one()方法使用 jQuery提供了简单的方法来向选择器(对应页面上的元素)绑定事件 ...
- [DOM Event Learning] Section 2 概念梳理 什么是事件 DOM Event
[DOM Event Learning] Section 2 概念梳理 什么是事件 DOM Event 事件 事件(Event)是用来通知代码,一些有趣的事情发生了. 每一个Event都会被一个E ...
- HTML DOM Event对象
我们通常把HTML DOM Event对象叫做Event事件 事件驱动模型 事件源:(触发事件的元素)事件源对象是指event对象 其封装了与事件相关的详细信息. 当事件发生时,只能在事件函数内部访问 ...
- [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 ...
随机推荐
- iOS项目开发实战——学会使用TableView列表控件(二)
要在iOS开发中使用TableView列表控件,不仅能够直接使用TableViewController作为整个主界面,并且还能够使用TableView控件来实现.使用TableView能够进行很多其它 ...
- PHP生成二维码方法
<?php //先下载一份phpqrcode类,下载地址http://down.51cto.com/data/780947require_once("phpqrcode/phpqrco ...
- C++的class的样例
私有就是仅仅可以通过内部调用,在类外面是不可以使用私有成员的 简单的写一个 Class A { public: //你能够通过公有的函数去訪问私有成员 Demo() //能够在这使 ...
- heap-adb shell查看堆栈使用
今天在使用eclipse中的heap查看oom的时候,发现手机(eng版本)非常的卡,后来换成usr版本,又连接不上eclipse.最后听别人说,可以使用adb shell进行查看.指令如下 adb ...
- ByteUtils
package sort.bing.com; import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import j ...
- 关于Webpack详述系列文章 (第四篇)
1. webpack基本概念 Entry:入口,Webpack 执行构建的第一步将从 Entry 开始,可抽象成输入.Module:模块,在 Webpack 里一切皆模块,一个模块对应着一个文件.We ...
- manjaro安装virtualbox教程
安装前需要知道 你需要知道你当前的内核版本 uname -r,比如输出了4.14.20-2-MANJARO那么你的内核版本为414 安装VirtualBox sudo pacman -S virtua ...
- linux下多进程的文件拷贝与进程相关的一些基础知识
之前实现了用文件IO的方式能够实现文件的拷贝,那么对于进程而言,我们是否也能够实现呢? 答案是肯定的. 进程资源: 首先我们先回想一下,进程的执行须要哪些资源呢?其资源包含CPU资源,内存资源,当然还 ...
- innodb next-key lock解析
參考http://blog.csdn.net/zbszhangbosen/article/details/7434637#reply 这里补充一些: (1)InnoDB默认加锁方式是next-key ...
- POJ1308——Is It A Tree?
Is It A Tree? Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 22631 Accepted: 7756 De ...