[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 ...
随机推荐
- 4.2.2 MINUS
4.2.2 MINUS正在更新内容,请稍后
- MongoDB + node-mongoskin简单演示样例
特点 无模式 MongoDB 中的每一条文档,都是一个 JSON 对象,因此你无需提前定义一个集合的结构,集合中的每一个文档也能够有不同的结构. 异步写入 MongoDB 默认全部的写操作都是『不安全 ...
- Android 学习笔记之Bitmap位图的缩放
位图的缩放也可以借助Matrix或者Canvas来实现. 通过postScale(0.5f, 0.3f)方法设置旋转角度,然后用createBitmap方法创建一个经过缩放处理的Bitmap对象,最后 ...
- css+ js 实现圆环时钟
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- scrollwidth ,clientwidth ,offsetwidth 三者的区别
clientwidth:内容可视区域的宽度 offsetwidth:元素整体宽度 scrollwidth:实际内容的宽度
- asp.net core系列 39 Razor 介绍与详细示例
原文:asp.net core系列 39 Razor 介绍与详细示例 一. Razor介绍 在使用ASP.NET Core Web开发时, ASP.NET Core MVC 提供了一个新特性Razor ...
- RGB 颜色空间转 HSI 颜色空间的matlab程序实现
RGB 颜色空间转 HSI 颜色空间的matlab程序实现 2014.10.20之前的内容有误,这里依据wikipedia更新了算法内容. 算法以wiki为准 https://en.wikipedia ...
- Elasticsearch中JAVA API的使用
1.Elasticsearch中Java API的简介 Elasticsearch 的Java API 提供了非常便捷的方法来索引和查询数据等. 通过添加jar包,不需要编写HTTP层的代码就可以开始 ...
- Log4j日志管理的简单实例
大型项目中非常多情况下要分析程序的日志信息,怎样管理自己的日志信息至关重要. 在应用程序中加入日志记录总的来说基于三个目的 , 监视代码中变量的变化情况,周期性的记录到文件里供其它应用进行统计分析工作 ...
- Logstash读写性能调整优化
继续