网站搜索

typescript - Angular - 如何设置 textarea 中的光标位置


我以为这会是一件容易的事情,但我意识到我根本不知道该怎么做。我有一个带有多行文本编辑功能的对话框。想法是,当你打开这个对话框并且已经有一些文本时,将光标设置到文本开头。所以我猜它的位置应该是0

起初我尝试在HTML中设置它,但它不起作用

<textarea
  matInput
  #textArea
  id="editExperimentTitleInput"
  [placeholder]="'experiment.title.placeholder' | translate"
  [(ngModel)]="title"
  autocomplete="off"
  spellcheck="false"
  [selectionStart]="0"
  [selectionEnd]="0"
  rows="10"
></textarea>

这也不起作用

@ViewChild('textArea') _textArea: ElementRef;

ngAfterViewInit(): void {
  const textArea = this._textArea.nativeElement as HTMLTextAreaElement;
  textArea.setSelectionRange(0, 0);
  //textArea.focus() // Throws expresion changed after....
}

我漏掉了什么?

答案#1

在 Angular 中聚焦元素通常是一个难以实现的事情。不过,看起来当使用 FormControl 而不是 ngModel 时,你的代码是可以工作的(可用的 Stackblitz 示例):

模板:

<textarea #textArea [formControl]="formControl"></textarea>

组件:

@ViewChild('textArea') _textArea: ElementRef;

formControl = new FormControl(this.title);

ngAfterViewInit(): void {
  const textArea = this._textArea.nativeElement as HTMLTextAreaElement;
  textArea.focus()
  textArea.setSelectionRange(0, 0);
}

模块(如果尚未添加,请将 ReactiveFormsModule 添加到 imports 中):

@NgModule({
  imports: [ BrowserModule, FormsModule, ReactiveFormsModule ]
})

你绝对需要 focus(),因为 setSelectionRange 只设置光标,如果没有焦点的话几乎没什么用。