setTimeout() 无法正常工作,如何在输入字段中获得焦点?

setTimeout() not working properly, How to get focus in input field?

我想在弹出模态加载时实现对输入的关注

HTML

<custom-input #name id="name" formControlName="name"
      ngDefaultControl  maxlength="3" minlength="2">
</custom-input>

弹窗-modal.component.ts

  @ViewChild('name', { static: true }) name: ElementRef;

parent.component.html

<popup-modal #childComponent" >
</popup-modal>

parent.component.ts

  openPopUp() {

this.popUpChild.popUp.nativeElement.open= true;
 setTimeout(() => {
   this.popUpchild.name.nativeElement.focus();
 }, 0);
}

我尝试从父级打开模态弹出窗口并在名称输入中设置焦点,但有时不是因为 setTimeout 而出现。如何在打开模态弹出窗口时每次都在名称输入字段中获得焦点?

问题是,当您将 open 变量设置为 true 时,该元素仍未在 HTML 中呈现。为此,您需要手动强制 Change Detection,而且您不需要再使用 setTimeout

parent.component.ts

constructor(private changeDetectorRef: ChangeDetectorRef) {}

openPopUp() {
    this.popUpChild.popUp.nativeElement.open= true;
    this.changeDetectorRef.detectChanges();
    this.popUpchild.name.nativeElement.focus();
}

将超时设置为 100。确保 z 顺序最高。焦点仅适用于最高层。

另外 DOM 渲染是在每个更新周期结束时完成的。当您设置一个小的超时延迟时,它会提供 DOM 的渲染时间。这意味着所有视图都已准备就绪。还有其他方法,但这是最简单的。

Z-order 将任何元素带到顶部。使用 material 个组件非常重要。