Where does DOM manipulation belong in Angular 2?

谁说我不能喝 提交于 2019-11-27 08:05:10

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;
  }
}

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 #.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!