Angular复制功能--ngxClipboard

ngx-clipboard适用angular2及更高的版本,且从angualr 6.0.0版本开始不再依赖任何js文件。

依赖条件
Angularngx-clipboard
2.x7.x.x
4.x8.x.x
5.x10.x.x
9.x.x13.x.x
安装方式
npm安装
npm install ngx-clipboard --save

yarn安装
yarn add ngx-clipboard --dev
使用

在所在的主(子)模块文件中引入,eg: app.module.ts, 导入

import { ClipboardModule } from 'ngx-clipboard';

imports: [
    ClipboardModule,
]
参数说明
  • ngxClipboard 指令 必选

  • cbContent 必选

    [cbContent]=“model” cbContent的值可以是其他input标签的ngModel,

    <input type="text" [(ngModel)]="text" placeholder="请输入内容">
    <button [ngxClipboard]="text">复制</button>
    

    也可以是字符串值[cbContent]="‘copy text’" (注意可以使用目标父容器来避免焦点陷阱问题)

    <button ngxClipboard [cbContent]="''copy text'">复制</button>
    

    也可以设定输入目标

    <input type="text" #target />
    <button [ngxClipboard]="target">Copy it</button>
    
  • 回调函数

    成功回调
    cbOnSuccess复制成功后触发回调属性$event: {isSuccess: true, content: string}

    <input type="text" [(ngModel)]="text" placeholder="请输入内容">
    <button type="button" ngxClipboard [cbContent]="text" 
    (cbOnSuccess)="successFun($event)">copy it</button>
    

    失败回调
    cbOnError复制失败时会触发回调属性$event:{isSuccess: false}

    <input type="text" [(ngModel)]="text" placeholder="请输入内容">
     <button type="button" ngxClipboard [cbContent]="text"
      (cbOnError)="errorFun($event)">copy it</button>
    

使用ClipboardService的copyFromContent() 复制任何您动态创建的文本。

import { ClipboardService } from 'ngx-clipboard'

constructor(private clipboardService: ClipboardService){
}

copy(text: string){
  this.clipboardService.copyFromContent(text)
}

您还可以使用结构指令* ngxClipboardIfSupported有条件地渲染宿主元素

<button ngxClipboard 
*ngxClipboardIfSupported 
[cbContent]="'target'" 
(cbOnSuccess)="isCopied = true">Copy</button>
全局复制处理

在全局范围内处理的副本响应,您可以订阅copyResponse$通过暴露ClipboardService

export class ClipboardResponseService {
  constructor(
    private _clipboardService: ClipboardService,
    private _toasterService: ToasterService
  ) {
    this.handleClipboardResponse();
  }

  handleClipboardResponse() {
    this._clipboardService.copyResponse$.subscribe((res: IClipboardResponse) => {
      if (res.isSuccess) {
        this._toasterService.pop('success', undefined, res.successMessage);
      }
    });
  }
}
每次复制剪贴板后,清理此模块使用的临时文本区域

默认情况下,仅在销毁指令时销毁它。如果您希望在每次复制到剪贴板后销毁它,请提供如下的根级模块配置.

ClipboardService.configure({ cleanUpAfterCopy: true });
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值