Manu
Manu

Reputation: 10944

How to perform DOM manipulation in Angular components?

How do we get hold of DOM elements in Angular (Version 2.x and above)? The basic functions like addClass, removeClass etc are not availble in typescript so how do we do these DOM manipulations in angular components? Please suggest if any. TIA

Upvotes: 13

Views: 26588

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657416

The basic functions like addClass, removeClass etc are not availble in typescript

They are available. Everything that can be done in JS can be done in TypeScript. You can also use jQuery while it's discouraged to be used with Angular2

Some explanation how to get a reference to an element angular 2 / typescript : get hold of an element in the template

That being said, in Angular2 you should avoid modifying the DOM imperatively but instead use binding with structural directives like *ngFor, *ngIf, ..., binding like [class.class-name']="true" or directives like ngClass.

For more details see https://angular.io/docs/ts/latest/guide/

Upvotes: 7

omeralper
omeralper

Reputation: 10114

You can reach your DOM elements by using ViewChild decorator in this way:

@Component({
    ....
    templateUrl: 'mytemplate.html'
})

export class MyComponent{
  @ViewChild('selector') private someName;
  constructor() {
     //this is your dom
     //this.someName.nativeElement
  }

}

and in your template class you got to specify who is that selector

<div #selector> </div>

or you can use ElementRef class

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

export class MyComponent  implements  AfterViewInit {

  constructor(protected elementRef: ElementRef) {

  }

  ngAfterViewInit() {
       //you can reach your dom element by using
       //this.elementRef.nativeElement
   }
}

You are free to use 3th party libs like Jquery for addClass, removeClass within typescript.

Upvotes: 12

Related Questions