效果如图
app.component.html
<div id="main">
<div id="leftBox"><textarea wrap="off" cols="2" id="leftNum" disabled [(ngModel)]="lineNum" #leftNum></textarea></div>
<textarea id="text-content" wrap="off" autofocus (keyup)="setCount($event)" [(ngModel)]="text_content" (paste)="onPaste($event)"
(cut)="onCut($event)" (scroll)="scroll($event)">
</textarea>
<button (click)="copyContentToClipboard()">copy</button>
</div>
app.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
@ViewChild("leftNum") leftNum: ElementRef;
lineNum: string="1";
text_content:string="";
contentForCopy: any="";
tableData: Array<any> = [];
constructor(){}
ngOnInit(){
}
calcLine(){
let num = "1\n";
let count = this.text_content.match(/\n/ig);
let linecount = count?count.length+1:1;
let i = 2;
while(i<=linecount){
num += i++ + "\n";
}
this.lineNum = num;
}
setCount(e){
if(["Enter", "Backspace", "Delete"].includes(e.code)){
this.calcLine();
}
}
onPaste(e){
setTimeout(this.calcLine.bind(this),0)
}
onCut(e){
setTimeout(this.calcLine.bind(this),0)
}
copy = (e)=>{
e.preventDefault();
if (e.clipboardData) {
e.clipboardData.setData('text/plain', this.contentForCopy);
}
}
copyContentToClipboard(){
this.contentForCopy = this.text_content;
window.addEventListener('copy', this.copy);
document.execCommand('copy');
window.removeEventListener('copy', this.copy);
}
scroll(e){
this.leftNum.nativeElement.scrollTop = e.target.scrollTop;
}
}
app.component.less
#main{
width: 100%;
#leftBox{
background:#ecf0f5;
width:5%;
// height:100%;
height: 360px;
text-align: left;
float: left;
#leftNum{
height:100%;
width: 100%;
resize: none;
outline:none;
overflow-y: hidden;
overflow-x: hidden;
border: 0;
background: rgb(247,247,247);
color: #999;
line-height: 24px;
font-size: 14px;
padding:10px 4px;
text-align: right;
font-weight: bold;
box-sizing: border-box;
}
}
#text-content{
border:1px solid #eaeaea;
outline:none;
width: 95%;
height: 360px;
resize: none;
background: rgb(250,250,250);
line-height: 24px;
font-size: 14px;
overflow:scroll;
float: left;
padding:10px 8px;
color: black;
font-family: inherit;
box-sizing: border-box;
}
}