Where does DOM manipulation belong in Angular 2?

后端 未结 2 1736
予麋鹿
予麋鹿 2020-12-01 11:20

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

相关标签:
2条回答
  • 2020-12-01 11:31

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

    0 讨论(0)
  • 2020-12-01 11:46

    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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题