Angular复制功能--ngxClipboard

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

依赖条件
Angular ngx-clipboard
2.x 7.x.x
4.x 8.x.x
5.x 10.x.x
9.x.x 13.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>
    

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

    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 });
    
发布了52 篇原创文章 · 获赞 34 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/YeShenLiaoSuiFeng/article/details/105276424
今日推荐