How to do DOM manipulation in Angular components?

How to get DOM elements in Angular (version 2.x and higher)? Basic functions like addClass, removeClass etc. are not available in typescript, so how do we do these DOM manipulations in Angular components? Please suggest if there are any. TIA

+4
source share
2 answers

Basic functions like addClass, removeClass etc. are not available in typescript

They are available. Everything that can be done in JS can be done in TypeScript. You can also use jQueryuntil it is recommended to use with Angular2

, angular 2/typescript:

Angular2 DOM, , *ngFor, *ngIf,..., [class.class-name']="true" ngClass.

. https://angular.io/docs/ts/latest/guide/

+5

DOM ViewChild :

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

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

}

,

<div #selector> </div>

ElementRef

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
   }
}

3- , JQuery addClass, removeClass typescript.

+5

Source: https://habr.com/ru/post/1660065/


All Articles