Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 205
Peter Avatar asked Nov 07 '16 12:11

Peter


People also ask

What is the best way to perform DOM manipulation in Angular 2?

EVENT BINDING : The flow of information from elements in a component to the corresponding component's class is event binding (HTML Template to TS) . Event binding works without having to define a template reference variable. This is the best and the easiest method to manipulate DOM elements.

Which method is used for DOM manipulation?

The jQuery after() method inserts content (new or existing DOM elements) after target element(s) which is specified by a selector.

Can TypeScript be used for DOM manipulation?

ts, one stands out among the rest: HTMLElement . This type is the backbone for DOM manipulation with TypeScript.


2 Answers

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.

like image 60
omeralper Avatar answered Oct 05 '22 13:10

omeralper


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/

like image 21
Günter Zöchbauer Avatar answered Oct 05 '22 13:10

Günter Zöchbauer