[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 ...
随机推荐
- Android资源推荐
Intellj IDEA 安装配置 使用IntelliJ IDEA 13搭建Android集成开发环境(图文教程) Android设计指南站点 图标 App Icon Template免费的Photo ...
- MongoDB(六)java操作mongodb增删改查
java操作mysql数据库的代码我们已经了如指掌了.增删改查,java对mongodb数据库也是类似的操作,先是数据库连接.再是进行操作. 首先我们进入进入admin数据库.然后建立自己的数据库te ...
- 使用QML自绘页面导航条
使用QML自绘页面导航条 近期使用QML制作项目,依照要求.须要制作成分页的插件.遗憾的是,QML的控件库Qt Quick都没有现成的控件,于是我尝试着自己实现自绘页面导航条. 原创文章,反对未声明的 ...
- thinkphp5多文件上传如何实现
thinkphp5多文件上传如何实现 一.总结 一句话总结:官方文档,测试一下,一定要测试,打印中间变量,就知道每句话是什么意思,一定要测试一下.又简单有快. 测试一下,你就能确定中间变量和你的是不是 ...
- css3的新特性选择器-------属性选择器
自己学css的时候比较乱,这次趁着复习把css3的新特性选择器和css2以前不怎么用的选择器做一个总结 <div id="parent"> <p>I'm a ...
- Json应用案例
Json应用案例之FastJson 这几天在网上找关于Json的一些案例,无意当中找到了一个我个人感觉比较好的就是阿里巴巴工程师写的FastJson. package com.jerehedu.f ...
- 洛谷——T1725 探险
http://codevs.cn/problem/1725/ 时间限制: 1 s 空间限制: 256000 KB 题目等级 : 钻石 Diamond 题解 查看运行结果 题目描述 Descri ...
- android图像处理系列之六--给图片添加边框(下)-图片叠加
前面介绍了一种用透明图片叠加的方式添加花边边框,下面将介绍另外一种图片叠加添加花边边框的方式.前面方法有一个缺点,就是做成PNG图片,图片体积会很大,不是一般的大,比同样的JPG大三倍多,如果项目可以 ...
- php课程 12-41 多态是什么
php课程 12-41 多态是什么 一.总结 一句话总结:一种请求,多种响应(根据参数类型和数量) 1.function useUsb(Usb $usb){}这句话是什么意思? 判断$usb参数是否实 ...
- 建堆是 O(n) 的时间复杂度证明。
建堆的复杂度先考虑满二叉树,和计算完全二叉树的建堆复杂度一样. 对满二叉树而言,第 \(i\) 层(根为第 \(0\) 层)有 \(2^i\) 个节点. 由于建堆过程自底向上,以交换作为主要操作,因此 ...