Home:ALL Converter>Where does DOM manipulation belong in Angular 2?

Where does DOM manipulation belong in Angular 2?

Ask Time:2016-05-22T23:54:03         Author:Chrillewoodz

Json Formatter

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?

Author:Chrillewoodz,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/37376442/where-does-dom-manipulation-belong-in-angular-2
Johannes :

Based upon recommend solution by developers: http://angularjs.blogspot.de/2016/04/5-rookie-mistakes-to-avoid-with-angular.html\n\n@Component({\n selector: 'my-comp',\n template: `\n <div #myContainer>\n </div>\n `\n})\nexport class MyComp implements AfterViewInit {\n @ViewChild('myContainer') container: ElementRef;\n\n constructor() {}\n\n ngAfterViewInit() {\n var container = this.container.nativeElement;\n console.log(container.width); // or whatever\n }\n}\n\n\nAttention: The view child name has to begin with myName and in the template you need #. ",
2016-07-01T14:42:42
yy