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
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.
The jQuery after() method inserts content (new or existing DOM elements) after target element(s) which is specified by a selector.
ts, one stands out among the rest: HTMLElement . This type is the backbone for DOM manipulation with TypeScript.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With