如何在 angular 中打开扩展面板时自动将编辑器聚焦在扩展面板内容中?

How to automatically focus the editor in the expansion panel content on open of expansion panel in angular?

我有一个带有“写回复”的扩展面板header。打开扩展面板,我有一个羽毛笔编辑器。

我需要将 quill 编辑器集中在扩展面板上。

<mat-expansion-panel #panel1>
<mat-expansion-header> <span>"Write a Response"</span> </mat-expansion-header>
<quill-editor [ngModel]="htmlText" (onContentChanged)="onContentChanged($event)" placeholder="placeholder"></quill-editor>
</mat-expansion-panel>

我试过自动对焦,cdkFocusInitial, (focus)="myMethod()",还是不行。有人可以帮忙吗?

谢谢。

要实现这一点,您必须使用@ViewChild。

首先给quil-editor添加一个id - #editor

<mat-expansion-panel #panel1>
<mat-expansion-header> <span>"Write a Response"</span> </mat-expansion-header>
<quill-editor #editor [ngModel]="htmlText" (onContentChanged)="onContentChanged($event)" placeholder="placeholder"></quill-editor>
</mat-expansion-panel>

然后转到 ts 文件并从 angular/core 导入 ViewChild 和 AfterViewInit。 然后

export class ComponentName implement AfterViewInit{
@ViewChild('editor') editorElementRef : ElementRef;

  ngAfterViewInit(){
    this.editorElementRef.nativeElement.focus();
  }
}

所以上面的代码,在视图初始化后将焦点移动到编辑器。