2017-11-15 13 views
0

私のページの最初のコントロールは、ページが最初に読み込まれたときに入力フォーカスを持っている必要があります。残念ながら、私の場合、コントロールはng-selectです。jqueryでng-selectを選択する

だから、どこかで私のAng2テンプレートで:私のngAfterViewInitで

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

、私が持っている:

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

可哀想に(また、div要素をドロップしようとした)、これが動作しません。

注: これは、「AngularJSの要素にデフォルトフォーカスを置く最も簡単な方法は何ですか?」とは異なります。その質問は入力コントロールを参照しているので、基本的なjquery focus/selectが機能します。これは特にng-select(束の子divとしてレンダリングする)を指しています。

+0

[AngularJSの要素にデフォルトのフォーカスを置くための最も簡単な方法は何ですか?](https://stackoverflow.com/questions/18920693の可能性のある重複/最も簡単な方法は、デフォルトでは、要素の中の要素に焦点を当てて) – APAD1

+0

ありがとう、その質問の重複はありません - それは入力コントロールを指しています。基本的なjqueryの選択が動作します。これは特にng-select(束の子divとしてレンダリングする)を指しています。 – Vman

答えて

1

あなたはjQueryのなしでそれを行うことができます:

@ViewChild('yourFieldReference') fieldRefName: ElementRef; 
 

 
. 
 
. 
 
. 
 
. 
 

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

私はinputでそれをやったが、あなたは、このコードは私のために働いた任意のHTML要素タグ

1

でそれを行うことができます、これを試してください

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

で、component.tsには、ビューチャイルドとレンダラーを使用して要素を取得します。 AfterViewInitは、HTMLがレンダリングされた後にフォーカスを合わせるのに役立ちます。 (のOnInit乗った問題()、その理由)

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

ありがとう、恥ずかしがって、私はang2のソリューションを使用するとは思わなかった! – Vman