如何自动对焦输入元素?类似于 this问题,但不是 AngularDart。像这样:
<input type="text" [(ngModel)]="title" [focus] />
//or
<input type="text" [(ngModel)]="title" autofocus />
Angular2 是否有任何构建支持此功能?
最好的结束问题是 this one ,但是有没有更短/更简单的解决方案,因为我没有“输入框列表”。在提供的链接中使用了 *ngFor="#input of inputs"
,但我在控件模板中只有 1 个输入。
最佳答案
这是我当前的代码:
import { Directive, ElementRef, Input } from "@angular/core";
@Directive({
selector: "[autofocus]"
})
export class AutofocusDirective
{
private focus = true;
constructor(private el: ElementRef)
{
}
ngOnInit()
{
if (this.focus)
{
//Otherwise Angular throws error: Expression has changed after it was checked.
window.setTimeout(() =>
{
this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
});
}
}
@Input() set autofocus(condition: boolean)
{
this.focus = condition !== false;
}
}
用例:
[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus
过时的代码(旧答案,以防万一):
我最终得到了这段代码:
import {Directive, ElementRef, Renderer} from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class Autofocus
{
constructor(private el: ElementRef, private renderer: Renderer)
{
}
ngOnInit()
{
}
ngAfterViewInit()
{
this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}
}
如果我将代码放在 ngOnViewInit
中,它不起作用。代码也使用最佳实践,因为直接调用元素焦点不是 recommended .
已编辑(条件自动对焦):
几天前我需要有条件的自动对焦,因为我隐藏了第一个自动对焦元素并且我想聚焦另一个,但只有当第一个不可见时,我以这段代码结束:
import { Directive, ElementRef, Renderer, Input } from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class AutofocusDirective
{
private _autofocus;
constructor(private el: ElementRef, private renderer: Renderer)
{
}
ngOnInit()
{
}
ngAfterViewInit()
{
if (this._autofocus || typeof this._autofocus === "undefined")
this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}
@Input() set autofocus(condition: boolean)
{
this._autofocus = condition != false;
}
}
编辑2:
Renderer.invokeElementMethod is deprecated而新的 Renderer2 不支持它。
所以我们回到原生焦点(它在 DOM 之外不起作用 - 例如 SSR!)。
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class AutofocusDirective
{
private _autofocus;
constructor(private el: ElementRef)
{
}
ngOnInit()
{
if (this._autofocus || typeof this._autofocus === "undefined")
this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
}
@Input() set autofocus(condition: boolean)
{
this._autofocus = condition != false;
}
}
用例:
[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus
关于Angular2+ 自动对焦输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41873893/