Search code examples
angularquillautofocusmat-expansion-panel

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


I have an expansion panel with "Write a response" header. On opening the expansion panel, I'm having a quill editor.

I need to focus the quill editor on expanding the panel.

<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>

I tried autofocus, cdkFocusInitial, (focus)="myMethod()", still not working. Can someone help?

Thanks.


Solution

  • To achieve this you will have to use @ViewChild.

    First Add an id to the quil-editor - #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>
    

    Then go over to the ts file and import ViewChild and AfterViewInit from angular/core. Then

    export class ComponentName implement AfterViewInit{
    @ViewChild('editor') editorElementRef : ElementRef;
    
      ngAfterViewInit(){
        this.editorElementRef.nativeElement.focus();
      }
    }
    
    

    So the above code, moves the focus to the editor once the view is initialized.