1

So im doing loop and display inputs and i want on click on select to add focus on first input element. Any suggestion how can i select that first element and add him autofoccus?

0

1 Answer 1

3

Here is how to do. Write a directive :

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', []);
    }
  }
}

in your component:

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 {

}

The corresponding plunker, adapted from this

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.