使用Angular2禁用文本框的剪切,复制和粘贴功能的指令 [英] Directive to disable Cut, Copy and Paste function for textbox using Angular2

查看:183
本文介绍了使用Angular2禁用文本框的剪切,复制和粘贴功能的指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Angular2来限制文本框中的复制和粘贴。但是我如何编写自定义指令,以便它可以很容易地应用于所有文本字段。

I am using Angular2 to restrict the copy and paste in textbox. But how do i write a custom directive, so that it will be easy to apply for all the text fields.

以下是限制复制和粘贴功能的工作代码。

Below is the working code to restrict the copy and paste functionality.

<ion-input formControlName="confirmpass" type="tel" (cut)="$event.preventDefault()" (copy)="$event.preventDefault()" (paste)="$event.preventDefault()"></ion-input>


推荐答案

您可以使用 HostListener 用于捕获剪切粘贴复制活动和然后使用 preventDefault()。这是一个例子

You can use a HostListener in your directive to catch cut, paste and copy events and then use preventDefault(). Here's an example

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

@Directive({
  selector: '[appBlockCopyPaste]'
})
export class BlockCopyPasteDirective {
  constructor() { }

  @HostListener('paste', ['$event']) blockPaste(e: KeyboardEvent) {
    e.preventDefault();
  }

  @HostListener('copy', ['$event']) blockCopy(e: KeyboardEvent) {
    e.preventDefault();
  }

  @HostListener('cut', ['$event']) blockCut(e: KeyboardEvent) {
    e.preventDefault();
  }
}

使用指令如此

<ion-input appBlockCopyPaste formControlName="confirmpass" type="tel"></ion-input>

工作演示

这篇关于使用Angular2禁用文本框的剪切,复制和粘贴功能的指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆