-1

The first control on my page needs to have input focus when the page initially loads, unfortunately, in my case, that control is an ng-select.

So, somewhere in my ang2 template:

<ng-select id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>

In my ngAfterViewInit, I have:

$("#mySelect > div").focus();
$("#mySelect > div").select();

(Also tried dropping the div)

Alas, this is not working.

Note: This is NOT a duplicate of "What is the easiest way to put a default focus on an element in AngularJS". That question is referring to an input control, so basic jquery focus/select works. This is specifically referring to an ng-select (which render as a bunch children div's).

Vman
  • 3,016
  • 2
  • 24
  • 20
  • Possible duplicate of [What is the easiest way to put a default focus on an element in AngularJS?](https://stackoverflow.com/questions/18920693/what-is-the-easiest-way-to-put-a-default-focus-on-an-element-in-angularjs) – APAD1 Nov 15 '17 at 17:17

2 Answers2

1

you could do it without jQuery:

@ViewChild('yourFieldReference') fieldRefName: ElementRef;

.
.
.
.

ngOnInit() {
 this.fieldRefName.nativeElement.focus();
}
<input #yourFieldReference id="fieldID">

I've done it with input but you could do it with any HTML element tag

Luca Taccagni
  • 1,059
  • 6
  • 23
1

This code worked for me, try this

<ng-select #myInput id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>

and in your component.ts, use viewchild and renderer to get the element. AfterViewInit helps to focus it after the html is rendered. (got issue on OnInit(), that why)

import {ViewChild, Component, AfterViewInit, ElementRef, Renderer} from 'angular2/core';

export class App {
  @ViewChild('myInput') selectFocus:ElementRef;

  constructor(private _renderer : Renderer) {

  }

  public ngAfterViewInit() {
    this._renderer.invokeElementMethod(this.selectFocus.nativeElement, 'focus', []);
  }
}
Veena K. Suresh
  • 942
  • 5
  • 16