我正在尝试在 Angular 5 中使用焦点进行 ng-select,但它不起作用
我正在使用 ng2-select
如何在 Angular 5 中使用焦点进行 ng-select ?
<label class="input">
<input (blur)="goTo()" type="text">
</label>
<label class="select" >
<div *ngIf="items.length > 0" >
<ng-select #select [items]="items">
</ng-select>
</div>
</label>
@ViewChild('select') myElement: ElementRef;
goTo(){
this.myElement.element.nativeElement.focus();
}
这对我来说效果很好,
@ViewChild('ngSelect') ngSelect: NgSelectComponent;
ngAfterViewInit() {
if (this.autofocus) {
setTimeout(() => {
this.ngSelect.focus();
});
}
}
改变这个
goTo(){
this.myElement.element.nativeElement.focus();
}
对此,
import { ChangeDetectorRef } from '@angular/core';
constructor (private cRef: ChangeDetectorRef) {}
// import 'SelectComponent' from your library for 'ng2-select'
goTo(){
let el = null;
if (this.items.length > 0) {
this.cRef.detectChanges();
el = (this.myElement.nativeElement as SelectComponent).element.nativeElement.querySelector('div.ui-select-container > input');
if (el) { el.focus(); }
}
}
您可能需要检查该元素是否已定义(或者您是否需要其中额外的“nativeElement”,但我基本上重用了here中的逻辑。
请注意,如果库更新以重命名这些类或修改模板,这可能不是一个稳定的修复。
希望有帮助。
一个简单的方法,你也可以这样做。
<label class="input">
<input (blur)="goTo(select)" type="text">
</label>
<label class="select">
<div *ngIf="items.length > 0">
<ng-select #select [items]="items">
</ng-select>
</div>
</label>
并在 Typescript 文件中。
goTo(select){
select.focus();
}
快速回复,在此解决方案中,记录每个选择元素以供将来使用(在本例中为模糊)。这需要根据您的情况进行调整。
import { Component, OnInit } from '@angular/core';
import { ViewChildren, QueryList } from '@angular/core';
@Component({
selector: 'app-editor',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.css']
})
export class EditorComponent implements AfterViewInit {
// Viewchildren
// https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
myindex:number;
@ViewChildren("select") inputs: QueryList<any>
constructor() {
this.myindex=0
}
// You will have to setup some input parameters in this function in order to switch to the right "select", (you have control)
private goTo()
{
// focus next input field
if (this.myindex +1 < this.inputs.toArray().length)
{
this.inputs.toArray()[this.myindex +1].nativeElement.focus();
this.myindex = this.myindex + 1;
}
else {
this.inputs.toArray()[0].nativeElement.focus();
this.myindex = 0;
}
}
private processChildren(): void {
console.log('Processing children. Their count:', this.inputs.toArray().length)
}
ngAfterViewInit() {
console.log("AfterViewInit");
console.log(this.inputs);
this.inputs.forEach(input => console.log(input));
// susbcribe to inputs changes, each time an element is added (very optional feature ...)
this.inputs.changes.subscribe(_ =>
this.processChildren() // subsequent calls to processChildren
);
}
}
将“#id”添加到 ngSelect 元素
<ng-select #id></ng-select>
然后添加:
@ViewChild('id') Ele: NgSelectComponent;
在 component.ts 文件中
然后使用:this.Ele.focus
进行对焦,它将对焦