简体   繁体   中英

How can I set focus for mat-input inside the mat-radio

I am trying to set the focus (the cursor to blink) on the input box on the click on the custom radio button. But it is not happening.I have stackblitz demo here .

so far I have tried.

<mat-radio-group [(ngModel)]="selection" #radioGroup="matRadioGroup">
  <mat-radio-button value="option 1">option 1</mat-radio-button>
  <mat-radio-button value="option 2">option 2</mat-radio-button>
  <mat-radio-button value="option 3">option 3</mat-radio-button>
  <mat-radio-button value="option 4">option 4</mat-radio-button>
  <mat-radio-button [value]="customOption" (click)="onBlur()">
    <mat-form-field>
      <input matInput id="input" [(ngModel)]="customOption" />
    </mat-form-field>
  </mat-radio-button>
</mat-radio-group>

in component

onBlur() {
      document.getElementById('input').focus();
   }

The problem is that it sets focus to the input element before the action of selecting the radio button completes so, once it does complete, it immediately switches the focus to the radio button.

One solution is to change

document.getElementById('input').focus();

to

setTimeout(() => document.getElementById('input').focus());

so that it waits a moment before setting focus to the input element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM