0

Like document.getElementById("id") in javascript, what we can do in angular2 and above versions to get dom element in type script?

I tried with angular.element but its not working

abc stack
  • 1
  • 1
  • 2
    You can use `ViewChild` decorator within your component class (see https://angular.io/api/core/ViewChild) – uminder Nov 13 '19 at 07:23

2 Answers2

1

There are multiple ways to do that. I am going to show one of them.

  1. You can use this.

    • document.querySelectorAll('.class-name')
    • document.querySelectorAll('#idname')
    • document.querySelectorAll('#tagname')

the working example is here

https://stackblitz.com/edit/angular-n8gau2

  1. You can use @viewChild as well

Component.ts

import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';


  @ViewChild('pRef', {static: false}) pRef: ElementRef;

    ngAfterViewInit() {
    console.log(this.pRef.nativeElement.innerHTML); 
    this.pRef.nativeElement.innerHTML = "DOM updated succesfully!!!"; 
  }
}

.html

<hello name="{{ name }}" ></hello>

<p #pRef>
  Start editing to see some magic happen :)
</p>

The working example is here

https://stackblitz.com/edit/angular-8-viewchild-example

You can find more info about ViewChild and it's usage here: https://angular.io/api/core/ViewChild

HaSnen Tai
  • 1,353
  • 2
  • 14
  • 22
0

It is against Angular's guidelines to directly modify the DOM. Instead use ViewChild(ren)() selector and modify the element using the Renderer2 service.

Ex:


<div #myDiv> </div>
...
@ViewChild('myDiv',{static:true}) myDiv:ElementRef;

constructor(private renderer:Renderer2){
this.renderer.setStyle(this.myDiv.elementRef,'style','value');
}
Bogdan B
  • 846
  • 9
  • 23
  • 1
    Just a note, it's a bad practice also using `ViewChild` to set a style. Yes, it should be preferred over `document.querySelector`, but use it only if you need to perform expensive actions that can't be easily made in the template. If your goal is to change the style, it's better using `[style]="..."` or `[style.property]="..."` in the template – Christian Vincenzo Traina Nov 13 '19 at 08:22
  • Good thing pointing this out. I was just giving a short example on how to combine the usage of `ViewChild` and `Renderer` . – Bogdan B Nov 13 '19 at 08:45