angularangularjs

How to get html element using renderer2 service in angular?


I am trying to get html textbox element using renderer2 service of angular/core to manipulate it. Although my code is not giving any error but it stops executing during execution on the line in which I am trying to get that element. that is - this.renderer.selectRootElement('#0', true).focus(); It is also setting up id of that text element as 0 which I am doing in initial lines.

Code begins from here--

private focusOnTextbox(){

    const inputElements = this.el.nativeElement.querySelectorAll('input');

    // Set ID for each input element
    inputElements.forEach((element: HTMLElement, index: number) => {
        const id = index.toString();
        this.renderer.setAttribute(element, 'id', id);
    });
    // Focus the input with id '0'
    this.renderer.selectRootElement('#0', true).focus();

    }

Solution

  • The main problem here was that this approach didn't works for 'id' start from numbers (eg- 0,1,2,3 and so on). So we have to give 'id' of html element starting from any alphabet or string(eg- myid1, myid2 and many more.).

    I just changed the id and it worked. :-)