在Angular中从文本区域复制到剪贴板

3

我正在尝试从HTML文本区域中复制文本,然而我只找到了一个使用Input标签的解决方案,就像这样:

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

功能:

copyInputMessage(inputElement){
  inputElement.select();
  document.execCommand('copy');
  inputElement.setSelectionRange(0, 0);
}

当我想用textarea标签替换input标签时,它不再起作用。是否有类似的简单解决方案适用于textarea?


你能发一下不工作的代码吗? - Prashant Pimpale
请查看此线程 https://dev59.com/HVoU5IYBdhLWcg3wO1UW - Naseer
2个回答

0

尝试这样做:

工作演示

<textarea type="text" #userinput></textarea>

0
<textarea cols="30" rows="4" [(ngModel)] = "userinput"></textarea>




<button (click)="copyInputMessage()" value="click to copy">Copy from Textbox</button>

在 Ts 文件中创建一个字符串类型的变量,并使用属性绑定将其与文本区域的值绑定。
 userinput: string;


copyInputMessage(this.userinput){
  inputElement.select();
  document.execCommand('copy');
  inputElement.setSelectionRange(0, 0);
}

如果您想使用模板引用,则:
<textarea cols="30" rows="4" #userinput></textarea>

在 Ts 文件中

@ViewChild('userinput') nameInputRef: ElementRef;

为什么要使用[(ngModel)]而不是模板引用变量? - Prashant Pimpale
请在答案中解释! - Prashant Pimpale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接