import { Component, OnInit, Input, ElementRef, ContentChild, TemplateRef, ViewContainerRef } from '@angular/core'; @Component({ selector: 'app-doc-viewer', templateUrl: './doc-viewer.component.html', styleUrls: ['./doc-viewer.component.scss'] }) export class DocViewerComponent implements OnInit { @Input() code: string; isShowIcon: boolean = false; constructor(private el: ElementRef) {} ngOnInit() {} ngAfterViewInit() { //console.log(this.el.nativeElement.querySelector('code')); } copyDoc() { const target = this.el.nativeElement.querySelector('code'); // 删除之前所有的选区 window.getSelection().removeAllRanges(); let range = document.createRange(); let selection = window.getSelection(); range.selectNode(target); selection.addRange(range); // 创建虚拟DOM 使用 document.execCommand (document.execCommand只能操作可编辑区域) const input = document.createElement('input'); input.setAttribute('value', selection.toString()); input.select(); if (document.execCommand('copy')) { document.execCommand('copy'); } } }