首页 > 解决方案 > 专注于 Angular 向导每一步的输入

问题描述

环境

要求

当用户移动到某个步骤时,我们需要让第一个(或特定的)元素获得焦点。每个步骤都有自己不同的元素(输入、按钮、下拉菜单等),这些元素应该会自动聚焦,因此用户不必手动单击该元素来启动流程。

代码尝试

  1. 在元素上使用autofocus标签。除了第一个元素之外,这与向导一样不起作用,整套步骤是一个单一的 DOM。
  2. 在每个步骤的组件中使用 ngOnViewEdit 事件和 ViewChild 来设置焦点

    ngOnViewEdit() { var emailElement = (this.email.nativeElement); if (emailElement) { emailElement.focus(); } else alert("找不到邮件元素"); 这也不起作用。还尝试使用setTimeout超时从 0 到 1000 的调用来包装方法的主体。

  3. 在向导的stepEnter尝试访问 ViewChild 并进行焦点尝试。这也失败了

组件界面

`<aw-wizard-step (stepEnter)="setFocus()">
    <app-cost-impact></app-cost-impact>
</aw-wizard-step>`

组件 TS

setFocus() { var emailComponent = <AddEmailComponent><unknown>this.wizard.currentStep; var emailElement = (<HTMLInputElement>emailComponent.email.nativeElement); if (emailElement) { emailElement.focus(); } else alert("Email element not found"); }

挑战

我们需要找出某种方法来访问每个步骤的元素,并使其足够通用以处理所有步骤

标签: htmlangulardomwizard

解决方案


这可以解决这个问题,只需将元素传递给setFocus方法然后运行焦点方法。

  setFocus(elm:HTMLElement){
    setTimeout(() =>{
       elm.focus();
    })
  }

模板

<aw-wizard>
 <aw-wizard-step stepTitle="Title of step 1" (stepEnter)="setFocus(email)">
        Content of Step 1
        <button type="button" awNextStep>Next Step</button>
        <button type="button" awNextStep>Go directly to third Step</button>
        <input type="text" placeholder="email" #email>
 </aw-wizard-step>
 <aw-wizard-step stepTitle="Title of step 2" awOptionalStep (stepEnter)="setFocus(age)">
        Content of Step 2
        <button type="button" awPreviousStep>Go to previous step</button>
        <button type="button" awNextStep>Go to next step</button>
        <input type="text" placeholder="age" #age>
 </aw-wizard-step>
</aw-wizard>

演示


推荐阅读