Home > Net >  Unable to set focus on angular editor using document.getelementById(id)
Unable to set focus on angular editor using document.getelementById(id)

Time:11-20

I am using dyanamic id for angular-editor. But I am unable to set the focus programatically.

I have tried the below code.

document.getElementById(id).focus();

But always occurs this error

ERROR TypeError: Cannot read properties of null (reading 'focus')

CodePudding user response:

Try this.

setTimeout(() => { document.getElementById(id).focus(); }, 500);

CodePudding user response:

Please place it in AfterViewInit

Please use the @ ViewChild()

CodePudding user response:

You need to set a @ViewChild to get access to the HTML element.

<mat-form-field >
            <mat-label >Name</mat-label>
            <input matInput formControlName"name" type="text" #myElement/>
</mat-form-field>

In the HTML mark the element you want to access in the ts Component with for ex. #myElement .

@ViewChild('myElement') firstItem: ElementRef;

....

ngAfterViewInit(): void {
    this.firstItem.nativeElement.focus();
  }

In the component you can then access that marked element with the @ViewChild.

  • Related