How to use Angular4 to set focus by element id

后端 未结 6 1472
無奈伤痛
無奈伤痛 2020-12-14 14:11

I am new to Angular, and am trying to use it to set focus on an input with the id \"input1\". I am using the following code:



        
6条回答
  •  孤城傲影
    2020-12-14 14:55

    Here is a directive that you can use in any component:

    import { NgZone, Directive, ElementRef, AfterContentInit, Renderer2 } from '@angular/core';
    
    @Directive({
        selector: '[appFocus]'
    })
    export class FocusDirective implements AfterContentInit {
        constructor(private el: ElementRef, private zone: NgZone, private renderer: Renderer2) {}
    
        ngAfterContentInit() {
            this.zone.runOutsideAngular(() => setTimeout(() => {
                this.renderer.selectRootElement(this.el.nativeElement).focus();
            }, 0));
        }
    }
    

    Use:

    
    

提交回复
热议问题