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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值