Как скопировать текстовое содержимое в буфер обмена в приложении Angular - PullRequest
0 голосов
/ 20 декабря 2018

У меня есть textarea в приложении Angular 7, и мне нужно скопировать его содержимое в буфер обмена после нажатия кнопки.Я использую этот код в обработчике нажатия кнопки:

if (this.txtConfigFile) {
    // Select textarea text
    this.txtConfigFile.nativeElement.select();

    // Copy to the clipboard
    document.execCommand("copy");

    // The following lines (in theory) unselect the text (DON'T WORK)
    this.txtConfigFile.nativeElement.value = this.txtConfigFile.nativeElement.value;
    this.txtConfigFile.nativeElement.blur();
}

ПРИМЕЧАНИЕ: txtConfigFile - это ссылка на элемент textarea, который я получаю, используя @ViewChild в объявлении компонента:

@ViewChild('txtConfigFile') txtConfigFile: ElementRef;

Это работает нормально, но текст в текстовой области остается выделенным, и я бы хотел этого избежать.Как можно отменить выбор текста после копирования в буфер обмена?

Спасибо.

Ответы [ 2 ]

0 голосов
/ 20 декабря 2018

Вместо этого добавьте this.txtConfigFile.nativeElement.setSelectionRange(0, 0); после выбора текста, чтобы отменить его выбор:

 if (this.txtConfigFile) {
  // Select textarea text
  this.txtConfigFile.nativeElement.select();

  // Copy to the clipboard
  document.execCommand("copy");

  // Deselect selected textarea
  this.txtConfigFile.nativeElement.setSelectionRange(0, 0);

}

DEMO

0 голосов
/ 20 декабря 2018

Решение 1 : скопировать любой текст

HTML

<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>

.ts файл

copyMessage(val: string){
    let selBox = document.createElement('textarea');
    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = val;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);
  }

Решение 2 : Копирование из текстового поля

HTML

<input type="text" value="User input Text to copy" #userinput>
      <button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>

.ts file

    /* To copy Text from Textbox */
  copyInputMessage(inputElement){
    inputElement.select();
    document.execCommand('copy');
    inputElement.setSelectionRange(0, 0);
  }

Демонстрация здесь

Решение 3: Импорт сторонней директивы ngx-clipboard

<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...