建立指令ng g directive shared/ccDirective/nextTab
html
指令的所有源碼:typescript
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 模板中調用this
<input type="text" next-tab> <input type="text" next-tab> <input type="text" next-tab>
ts 控制器中初始化code
@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
進行初始化便可htm