Angular2 - Focusing a textbox on component load

前端 未结 10 1538
刺人心
刺人心 2020-12-02 16:29

I am developing a component in Angular2 (Beta 8). The component has a textbox and a dropdown. I would like to set the focus in textbox as soon as component is loaded or on c

10条回答
  •  情深已故
    2020-12-02 17:05

    I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.

    For router changes:

    router.events.subscribe((val) => {
        setTimeout(() => {
            if (this.searchElement) {
                this.searchElement.nativeElement.focus();
            }
        }, 1);
    })
    

    Then ngAfterViewInit() for the onload scenario.

提交回复
热议问题