如何将按钮复制到剪贴板的输入值?
我见过这个:How do I copy to clipboard in Angular 2 Typescript?
但它不再与ngModule(RC5 +)的最新角度变化相容
答案 0 :(得分:1)
您可以使用许多不同的库以几种不同的方式完成此任务。问题是,它们没有很好的文档记录,并且是特定于用例的。花一些时间来了解角度/核心的文档。这是我最终得到的解决方案:
import { Component, OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor( @Inject(DOCUMENT) private document: Document ) {
}
ngOnInit() {
}
onCopy() {
var el = this.document.getElementById('targetDiv')
el.setAttribute('contenteditable','true')
el.focus()
this.document.execCommand('selectAll')
this.document.execCommand('copy');
el.setAttribute('contenteditable','false')
el.blur()
}
}
在模板中
<div id="targetDiv" contenteditable="false">
<p><strong>Test: </strong> 1 2 3 4 </p>
<h2> mic check </h2>
</div>
<button mat-raised-button (click)="onCopy()" >
Copy
</button>
答案 1 :(得分:0)
以下是 RC7版本。
工作演示:https://plnkr.co/edit/hSP42BLoxX2uodZZ2uMj?p=preview
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import {ClipboardDirective} from './clipboard.directive';
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ AppComponent,ClipboardDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
答案 2 :(得分:0)
这是一个简单的纯Angular2和javascript解决方案,不需要任何库,可以在angular组件中使用。您可以将其转变为服务,或者在需要时使其更通用,但这将确立基本思想。
当前,浏览器仅允许将文本从或中的“选择”复制到剪贴板。可以在div中实现
(.html file)
<div id="inputId">Some texts</div>
<button (click)="copyToClipboard()'>click me</button>
//(.ts file)
public copyToClipboard(){
var el = document.getElementById('inputId');
el.setAttribute('contenteditable','true');
el.focus();
document.execCommand('selectAll');
document.execCommand('copy');
el.setAttribute('contenteditable','false');
el.blur();
}