How to set focus on an element inside a component inside a Mat Dialog?

166 views Asked by At

I'm aware of the property autoFocus, that can receive a CSS Selector to focus an element when a MatDialog is open. I need to target a submit button that is inside the component <wknw-dialog-actions></wknw-dialog-actions>, how can I target that?

Here's a complete dialog component structure for better visualization:

contact-group-edit.component.ts (which is a dialog, opened by matDialog.open...)

<form [formGroup]="contactGroupForm" [appConnectForm]="contactGroup$ | async">
  <wknw-dialog-title (closeEvent)="close()"> {{title}} </wknw-dialog-title>
  <wknw-dialog-content>
    <mat-form-field>
      <mat-label i18n>Name</mat-label>
      <input matInput formControlName="name" />
    </mat-form-field>
  </wknw-dialog-content>

  <wknw-dialog-actions <-- my submit button is inside this component -->
    (confirmEvent)="save()"
    (closeEvent)="close()"
    [dialogType]="dialogType"
    [submitDisabled]="!contactGroupForm.valid"
  ></wknw-dialog-actions>
</form>

wknw-dialog-actions.component.ts

<div #ref><ng-content></ng-content></div>
<ng-container *ngIf="!ref.hasChildNodes()">
    <button mat-raised-button mat-dialog-close *ngIf="showButtonCancel" (click)="closeAction()" i18n>
        Cancel
    </button>


// button that needs to be focused below


    <button mat-raised-button [disabled]="submitDisabled" [color]="confirmButtonColor" (click)="confirmAction()" class="btn-confirm-action">
        {{confirmButtonTitle}}
    </button>
</ng-container>

I've tried setting an id to the component itself, like:

<wknw-dialog-actions id="actions"... and targetting the submit button like:

const dialogConfig: MatDialogConfig = {
    autoFocus: '#actions .btn-confirm-action'
}

Unsuccessful.

1

There are 1 answers

1
Magashegyi Ádám On
var btn = document.getElementById("id of button");
btn.focus();