# Angular how to get an element by id

ViewChild

The most angular way to get an element by id in a component’s template is to basically add a reference on the html element and get it through the @ViewChild() selector.

my-component.html

<div #targetElement id="target"><p>Hello</p></div>

my-component.ts

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html'
})
export class MyComponent {

 @ViewChild('targetElement'): targetElement: ElementRef;

 ngAfterViewInit()  {
 	console.log(this.targetElement.nativeElement);
 }
}

You can even write @ViewChild(’targetElement’, { static: true }) to access the element from the ngOnInit lifecycle. The element is considered “static” and will be accessible before the change detection runs.

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html'
})
export class MyComponent {

 @ViewChild('targetElement', { static: true }): targetElement: ElementRef;

 ngOnInit()  {
 	console.log(this.targetElement.nativeElement);
 }
}

Angular dom manipulation

By injecting the Document object, we can still access the dom.

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html'
})
export class MyComponent {

 constructor (@Inject(DOCUMENT) private document: Document) {

 }
 ngOnInit()  {
 	console.log(document.getElementById('target'));
 }
}

Another option is to find the element from the component’s ElementRef.

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html'
})
export class MyComponent {

 constructor (private elementRef: ElementRef) {

 }
 ngOnInit()  {
 	console.log(this.elementRef.nativeElement.querySelector('#target'));
 }
}

While the Dom manipulation works, overall it is not recommended to access the dom directly.