2017-03-16 35 views
5

当模板中的div更改大小时执行某些操作的最佳方式是什么?调整窗口大小时,div的大小会发生变化。使用Rxjs Observable /订阅还是以其他方式?如何观察Angular 2中元素大小的变化

模板:

<div #eMainFrame class="main-frame"> 
    ... 
</div> 

组件:

@Component({ 
    selector: 'app-box', 
    templateUrl: './box.component.html', 
    styleUrls: ['./box.component.css'] 
}) 
export class BoxComponent implements OnInit { 
    @ViewChild('eMainFrame') eMainFrame : ElementRef; 

    constructor(){} 

    ngOnInit(){ 
    // This shows the elements current size 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
    } 
} 

更新组件(本实施例中检测当窗口尺寸被改变)

constructor(ngZone: NgZone) { 

    window.onresize = (e) => { 
    ngZone.run(() => { 
     clearTimeout(this.timerWindowResize); 
     this.timerWindowResize = setTimeout(this._calculateDivSize, 100); 
    }); 
    } 
} 

_calculateDivSize(){ 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
} 

但是这给我一个错误:

EXCEPTION: Cannot read property 'nativeElement' of undefined

+0

您是否尝试过'element.resize'?这可能有所帮助:http://stackoverflow.com/questions/21170607/angularjs-bind-to-directive-resize – Rajesh

回答

4

的浏览器不提供任何东西,因此你需要轮询值时运行角度变化检测

ngDoCheck()被调用。我认为这是做检查的好去处:

ngDoCheck() { 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
} 

如果您只需要组件创建后检查一次,使用

ngAfterContentInit(){ 
    // This shows the elements current size 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
} 
+0

ngDoCheck可以工作,但ngDoCheck()会被调用很多次。 – user3800924

+1

每次更改检测运行。这取决于您的具体要求,以及是否有一个事件,您可以利用更好的时机阅读尺寸。 –