Working with the DOM in Angular 2 / 4 Applications
In order to interact with the DOM within Angular 2/4 applications, we must utilize the ngAfterViewInit()
method of the AfterViewInit
interface. This method is triggered once the bindings of child directives have been validated for the first time, essentially when the view is initially displayed.
When utilizing @ViewChild
, it grants access to the nativeElement
. Nevertheless, it is advised to refrain from directly interacting with the nativeElement
inside ngAfterViewInit()
due to potential browser safety issues and lack of support for web workers, which are unaware of DOM updates.
The recommended approach involves employing the renderer
instead. The renderer should be injected into the component's constructor, and an identifier reference must be provided for the HTML element on the view, such as:
<p #p1></p>
Subsequently, this can be accessed in the corresponding component's .ts
file like so:
export class SampleComponent implements AfterViewInit {
@ViewChild("p1") p1;
constructor(private renderer: Renderer2)
{ }
ngAfterViewInit() {
// preferred DOM manipulation technique
this.renderer.setStyle(this.p1.nativeElement,
'color',
'red');
// not recommendable DOM manipulation strategy
//this.p1.nativeElement.style = "color:blue;";
}
}