如何在循环中的第一个输入元素上添加自动对焦?

时间:2017-07-12 20:31:49

标签: angular

所以我正在做循环和显示输入,我想点击选择以在第一个输入元素上添加焦点。有什么建议我如何选择第一个元素并添加autofoccus?

1 个答案:

答案 0 :(得分:1)

这是怎么做的。写一个指令:

import {Directive, Renderer, ElementRef, OnInit, AfterViewInit, Input} from '@angular/core';

@Directive({
  moduleId: module.id,
  selector: '[focusOnInit]'
})
export class FocusOnInitDirective implements OnInit, AfterViewInit {
  @Input() focusOnInit ;

  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) =>  i.focusOnInit===0)) {
      this.renderer.invokeElementMethod(
        this.elementRef.nativeElement, 'focus', []);
    }
  }
}
组件中的

import { Component } from '@angular/core';
@Component({
  moduleId: module.id,
  selector: 'app',
  template: `
    <div *ngFor="let input of [1,2,3,4]; let i=index">
      <input  type="text" [focusOnInit] = i >
    </div>
  `
})
export class AppComponent {

}

相应的plunker,改编自this