java对焦_Angular2自动对焦输入元素

这是我目前的代码:

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

Outdated code (old answer, just in case):

我最终得到了这段代码:

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 .

Edited (conditional autofocus):

几天前我需要条件自动对焦,因为我隐藏了第一个自动对焦元素,我想要聚焦另一个,但只有当第一个不可见时,我结束了这段代码:

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;

}

}

Edited2:

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


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部