How to get width of (DOM) Element in Angular2

后端 未结 4 1794
栀梦
栀梦 2020-12-15 03:32

there a some similiar threads but I couldn\'t find a suitable answer for my needs. So that direct DOM access should be strictly avoided in angular2 I\'m just wondering whats

4条回答
  •  孤街浪徒
    2020-12-15 04:07

    I don't know a way to get the width from the host element without accessing nativeElement but setting could be done like:

    @HostListener('window:resize', ['$event.target']) 
    onResize() { 
      this.resizeWorks();
    }
    
    @HostBinding('style.height.px')
    elHeight:number;
    
    private resizeWorks(): void {
      this.elHeight = this.el.nativeElement.width;
    }
    

    If you can add an element inside your components template like

    then this would work without direct DOM access at all (but not after init).

提交回复
热议问题