How to perform DOM manipulation in Angular compone

2020-01-30 08:19发布

问题:

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

回答1:

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.



回答2:

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/