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>
使用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 });