Angular 模擬鍵盤事件 回車切換焦點

  • 建立指令
    ng g directive shared/ccDirective/nextTabhtml

    指令的所有源碼: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

  • 源碼百度網盤 -> 源碼 -> Angular -> 回車切換到下一個控件 自定義指令改進版.zip
相關文章
相關標籤/搜索