How to perform DOM manipulation in Angular components?

℡╲_俬逩灬. 提交于 2019-12-28 05:31:10

问题


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/



来源:https://stackoverflow.com/questions/40464794/how-to-perform-dom-manipulation-in-angular-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!