Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing DOM in Angular 2 RC

Tags:

angular

What is the proper way to manipulate the DOM in Angular 2 RC?

For instance, I'm building a service for debug purposes to swap out .css file references in the document .

Prior to Angular 2 RC, it was possible to use BrowserDomAdapter from DOM manipulations, like so:

import { BrowserDomAdapter } from 'angular2/platform/browser';

...
constructor(private domAdapter: BrowserDomAdapter) {
}
...

const document = this.domAdapter.defaultDoc();

This was inspired by the Title service (now in @angular/platform-browser). It seems that the Title service still uses it internally, but it is no longer exported for use outside of Angular. I.e.

import { BrowserDomAdapter } from "@angular/platform-browser";

Results in:

Module '".../@angular/platform-browser/index"' has no exported member 'BrowserDomAdapter'
like image 300
Ronald Zarīts Avatar asked May 06 '16 09:05

Ronald Zarīts


People also ask

How do you read the DOM element in angular 6?

Steps:Use template reference and ViewChildren() to get HTML element. Inject Renderer and ElementRef into the constructor. Use the removeChild() method of the renderer to remove the child component. To get the host element, we need to use ElementRef.

How does angular manipulate the DOM?

Manipulating the DOM is easy with Angular. We can directly access the element by using ElementRef provided by @angular/core . If you manipulate it by using a directive (common use case) — most are likely to use nativeElement directly like this: It will correctly change the color of the element.

How do you find the element reference?

We use the ViewChild to get the ElementRef of an HTML element in the component class. Angular also inject ElementRef of the Host element of the component or directive when you request for it in the constructor.


2 Answers

  import {BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter';

UPDATE:(comment)

an issue on GitHub explains that the removal was indeed accidental, so hopefully it will be back in rc2. - @paul

like image 86
Ankit Singh Avatar answered Oct 26 '22 10:10

Ankit Singh


For people like me, looking forward for interacting with the DOM in angular 2.4:

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Component({})
export class MyClass {

    constructor (@Inject(DOCUMENT) private document) { }

    doSomething() {
        this.document.someMethodOfDocument();
    }
}

You should not use any adapter. This is implementation detail and should not be used. Instead @Inject(DOCUMENT) into your component and use it.

Further reading: https://github.com/angular/angular/issues/8509

like image 26
Stefan Rein Avatar answered Oct 26 '22 09:10

Stefan Rein