html - 专注于 Angular 向导每一步的输入
问题描述
环境
- 角 8
- AZ-向导
要求
当用户移动到某个步骤时,我们需要让第一个(或特定的)元素获得焦点。每个步骤都有自己不同的元素(输入、按钮、下拉菜单等),这些元素应该会自动聚焦,因此用户不必手动单击该元素来启动流程。
代码尝试
- 在元素上使用
autofocus
标签。除了第一个元素之外,这与向导一样不起作用,整套步骤是一个单一的 DOM。 在每个步骤的组件中使用 ngOnViewEdit 事件和 ViewChild 来设置焦点
ngOnViewEdit() { var emailElement = (this.email.nativeElement); if (emailElement) { emailElement.focus(); } else alert("找不到邮件元素"); 这也不起作用。还尝试使用
setTimeout
超时从 0 到 1000 的调用来包装方法的主体。在向导的
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");
}
挑战
我们需要找出某种方法来访问每个步骤的元素,并使其足够通用以处理所有步骤
解决方案
这可以解决这个问题,只需将元素传递给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>
推荐阅读
- visual-studio - 为 iis 上托管的 webforms 项目调试 javascript
- android - 如何在android中为高优先级通知覆盖静音/静音和振动
- amazon-web-services - 使用 CloudFormation 更新 DynamoDB 的 TimeToLiveSpecification
- python - 为什么在以图像为背景的不同 Tkinter 画布之间切换时会出现快速的白色闪烁?
- flask - 联系人无法为映射表组装任何主键列
- sql - Oracle SQL 数据库表列重要性
- google-chrome - 这些恶意代码在我的 chrome 浏览器的所有页面中
- node.js - Angular/ MongoDB/ NodeJs:从一个域自动登录到另一个域
- react-native - TypeError:在使用 createAsyncThunk 和 createSlice 时无法读取 redux 工具包中未定义的属性“待定”(@reduxjs/toolkit”:“^1.4.0)
- google-apps-script - 谷歌表格脚本:从当前单元格获取多列/行命名范围