Focus on newly added input element

前端 未结 5 1531
臣服心动
臣服心动 2020-11-22 15:28

I have a new Angular 2 app with a list of input boxes. When the user hits the return key, I add a new input box immediately after the one they\'re

5条回答
  •  甜味超标
    2020-11-22 16:02

    In order to prioritize which element will get focus when initializing several directives in same cycle, use:

    Directive:

    @Directive({
      selector: '[focusOnInit]'
    })
    export class FocusOnInitDirective implements OnInit, AfterViewInit {
      @Input('focusOnInit') priority: number = 0;
    
      static instances: FocusOnInitDirective[] = [];
    
      constructor(public renderer: Renderer, public elementRef: ElementRef) {
      }
    
      ngOnInit(): void {
        FocusOnInitDirective.instances.push(this)
      }
    
      ngAfterViewInit(): void {
        setTimeout(() => {
          FocusOnInitDirective.instances.splice(FocusOnInitDirective.instances.indexOf(this), 1);
        });
    
        if (FocusOnInitDirective.instances.every((i) => this.priority >= i.priority)) {
          this.renderer.invokeElementMethod(
            this.elementRef.nativeElement, 'focus', []);
        }
      }
    }
    

    Usage:

    
    

    https://plnkr.co/edit/T9VDPIWrVSZ6MpXCdlXF

提交回复
热议问题