简体   繁体   English

如何在Mat收音机内为Mat输入设置焦点

[英]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 . 但是这没有发生。我在这里有stackblitz演示。

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. 以便在将焦点设置到输入元素之前需要稍等片刻。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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