In an Angular component, I display real-time data in a very complex way that requires the use of ElementRef
for various purposes supporting UI interaction.
this.elRef.nativeElement.querySelector('.my-element')
As a result, I am running into a few rare use cases when referencing an element this way throws a null
error because the element is either not yet accessible in the DOM or had been previously removed due to real-time data updates inside an *ngFor
.
To prevent errors, I am checking the native element for null
:
if(this.elRef.nativeElement.querySelector('.my-elment') != null) {
// reference or set style on this element
}
This works fine, but is there a better approach? I have wound up with a lot of these if
statements throughout my component as a result.
I have made every effort to avoid touching the DOM and to avoid running into the possibility for an element to be null
otherwise in my template, but I am stuck with some rare cases that are just unavoidable.
Any advice greatly appreciated.