Where does DOM manipulation belong in Angular 2?

21,994

Solution 1

Direct DOM manipulation should be avoided entirely in Angular2.

Use instead bindings like:

export class MyComponent {
  constructor() {
    this.setHeight();
  }

  @HostBinding('style.height.px')
  height:number;

  @HostListener('window:resize', ['$event'])
  setHeight() {
    this.height = window.innerHeight;
  }
}

Solution 2

Based upon recommend solution by developers: http://angularjs.blogspot.de/2016/04/5-rookie-mistakes-to-avoid-with-angular.html

@Component({
  selector: 'my-comp',
  template: `
    <div #myContainer>
    </div>
  `
})
export class MyComp implements AfterViewInit {
  @ViewChild('myContainer') container: ElementRef;

  constructor() {}

  ngAfterViewInit() {
    var container = this.container.nativeElement;
    console.log(container.width); // or whatever
  }
}

Attention: The view child name has to begin with myName and in the template you need #.

Share:
21,994
Chrillewoodz
Author by

Chrillewoodz

I love green numbers.

Updated on July 02, 2020

Comments

  • Chrillewoodz
    Chrillewoodz almost 4 years

    In Angular 1 all DOM manipulation should be done in directives to ensure proper testability, but what about Angular 2? How has this changed?

    I've been searching for good articles or any information at all about where to put DOM manipulation and how to think when doing it, but I come up empty every time.

    Take this component for example (this is really a directive but let's pretend that it's not):

    export class MyComponent {
    
      constructor(private _elementRef: ElementRef) {
    
        this.setHeight();
    
        window.addEventListener('resize', (e) => {
          this.setHeight();
        });
      }
    
      setHeight() {
        this._elementRef.nativeElement.style.height = this.getHeight() + 'px';
      }
    
      getHeight() {
        return window.innerHeight;
      }
    }
    

    Does event binding belong in a constructor for example, or should this be put in the ngAfterViewInit function or somewhere else? Should you try to break out the DOM manipulation of a component into a directive?

    It's all just a blur at the moment so I'm not sure that I'm going about it correctly and I'm sure I'm not the only one.

    What are the rules for DOM manipulation in Angular2?

  • Chrillewoodz
    Chrillewoodz almost 8 years
    Can you elaborate?
  • Günter Zöchbauer
    Günter Zöchbauer almost 8 years
    @HostListener(...) registers an event listener and @HostBinding(...) updates the height style value to the value assigned to number. The event handler wasn't correct. I updated my answer (sorry, was only on the phone when I wrote it).
  • Günter Zöchbauer
    Günter Zöchbauer almost 8 years
    Direct DOM manipulation is not compatible with server-side rendering and utilizing Angulars WebWorkers support.
  • Chrillewoodz
    Chrillewoodz almost 8 years
    Hmm ok, I kinda understand but I don't quite understand this one @HostBinding('style.height.px') height:number;, what does the height:number part do?
  • Chrillewoodz
    Chrillewoodz almost 8 years
    This seems to suggest that the listener will listen to the host element for resize rather than the window?
  • Günter Zöchbauer
    Günter Zöchbauer almost 8 years
    Sorry, I missed the window. Updated my answer.
  • Chrillewoodz
    Chrillewoodz almost 8 years
    Just found the answer while reading through the dart docs, lol. Thanks anyway :) Will have a lot of rewriting to do now... Sigh.
  • superluminary
    superluminary over 7 years
    This may be true, and in many cases including the one above, a binding is sufficient. There are many instances though where DOM manipulation is necessary and a template is just not sufficient. Angular 1 gave us the link function as an escape hatch.
  • Günter Zöchbauer
    Günter Zöchbauer over 7 years
    I'm aware that there are use cases where this is hard or impossible but this is what you should strive for. I don't know much about Angular1. You can manipulate the DOM in Angular2 as well, but that has it's drawbacks if you want to use WebWorkers or server-side rendering. You can also use ViewContainerRef.createComponent() to dynamically add/remove components and even create components at runtime.
  • JK Dennis
    JK Dennis over 7 years
    Don't forget to add the appropriate imports: import { AfterViewInit, ViewChild } from '@angular/core'; code excerpt from: angular.io/docs/ts/latest/cookbook/…
  • Brian Riley
    Brian Riley about 7 years
    You'll also need to include import { ElementRef } from '@angular/core';
  • Konrad Viltersten
    Konrad Viltersten about 7 years
    Are you saying that the prefix my must be present in the name? Or did you mean that the name we refer to in @ViewChild('whatever') must correspond to #whatever in the markup of the template?
  • Nathan
    Nathan almost 7 years
    @KonradViltersten It is probably no longer relevant to you, but it might still be relevant to others; the "my" prefix does not have to be present in the name, it just has to be the same, but it is highly recommended to use a personal/custom prefix so that it won't interfere with other modules.