如何通过绑定设置焦点元素?

alm*_*mog 11 angular

在Angular2中,如何在元素焦点上设置绑定.我不想用elementRef设置它.我认为在AngularJS中有ngFocus指令在Angular2中没有这样的指令

MrB*_*ise 18

渲染服务现已弃用(如角4.x版的)新Renderer2服务没有invokeElementMethod.你可以做的是获得这样的元素的引用:

const element = this.renderer.selectRootElement('#elementId');
Run Code Online (Sandbox Code Playgroud)

然后您可以使用它来关注该元素,如下所示:

element.focus();
Run Code Online (Sandbox Code Playgroud)

更多关于如何selectRootElement工作在这里:

编辑:

如果元素没有集中,那么常见的问题是元素没有准备好.(例如:禁用,隐藏等).你可以这样做:

setTimeout(() => element.focus(), 0);
Run Code Online (Sandbox Code Playgroud)

这将创建一个将在下一个VM转弯中运行的macrotask,因此如果启用该元素,焦点将正常运行.


Ang*_*hub 16

一个简单的"焦点"指令

import {Directive, Input, ElementRef} from 'angular2/core';
@Directive({
    selector: '[focus]'
})
class FocusDirective {
    @Input()
    focus:boolean;
    constructor(@Inject(ElementRef) private element: ElementRef) {}
    protected ngOnChanges() {
        this.element.nativeElement.focus();
    }
}

// Usage
@Component({
    selector : 'app',
    template : `
        <input [focus]="inputFocused" type="text">
        <button (click)="moveFocus()">Move Focus</button>
    `,
    directives: [FocusDirective]
})
export class App {
    private inputFocused = false;
    moveFocus() {
        this.inputFocused = true;
        // we need this because nothing will 
        // happens on next method call, 
        // ngOnChanges in directive is only called if value is changed,
        // so we have to reset this value in async way,
        // this is ugly but works
        setTimeout(() => {this.inputFocused = false});
    }
}
Run Code Online (Sandbox Code Playgroud)


Dim*_*oid 9

我尝试了两种变体,但没有一种适合简单使用.1st(由@AngJobs)在组件中需要额外的工作,你使用指令(设置focus = true),第二个(由@ShellZero)完全不工作,因为在视图实际准备好之前调用的焦点.所以我把焦点转移到了ngAfterViewInit.现在你可以添加<input focus...并忘记它.元素将在视图init之后自动获得焦点.

import { Directive, ElementRef, Renderer, AfterViewInit } from '@angular/core';
@Directive({
    selector: '[focus]'
})

export class DmFocusDirective implements AfterViewInit {
    constructor(private _el: ElementRef, private renderer: Renderer) {
    }

    ngAfterViewInit() {
        this.renderer.invokeElementMethod(this._el.nativeElement, 'focus');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:“Renderer”已被弃用,并且 Angular 团队不打算将“invokeElementMethod()”引入“Renderer2”。https://github.com/angular/angular/issues/13818 (2认同)