• 创建指令
    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

葬天尘
354 声望7 粉丝

引用和评论

0 条评论