-
创建指令
ng g directive shared/ccDirective/nextTab
指令的全部源码:
import { Directive, HostListener, ElementRef } from '@angular/core'; @Directive({ selector: '[next-tab]' }) export class NextTabDirective { self:any; nextControl:any; @HostListener("keydown.enter", ["$event"]) onEnter(event: KeyboardEvent) { if (this.nextControl) { if (this.nextControl.focus) { this.nextControl.focus(); this.nextControl.select(); event.preventDefault(); return false; } } } constructor(private control: ElementRef) { this.self=control.nativeElement; } }
-
html 模板中调用
<input type="text" next-tab> <input type="text" next-tab> <input type="text" next-tab>
-
ts 控制器中初始化
@ViewChildren(NextTabDirective) inputs: QueryList<NextTabDirective>; initTab(){ const controls=this.inputs.toArray(); for (let i=0;i<controls.length-1;i++){ controls[i].nextControl=controls[i+1].self; } }
在生命周期钩子
ngAfterViewInit
里调用initTab
进行初始化即可 -
源码
百度网盘 -> 源码 -> Angular -> 回车切换到下一个控件 自定义指令改进版.zip
- 下面是后续对UI套件支持的测试:
- 2019年1月10日 22:16:49
测试ng-zorro-antd
的nz-input
兼容 - 2019年1月10日 22:22:53
测试PrimeNG
的pInputText
兼容 - 2019年1月10日 22:34:51
测试表单中的nz-input
兼容 - 2019年1月10日 22:38:24
测试表单中的pInputText
兼容 -PrimeNG
的input
组件