2017-03-16 38 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

每次更改檢測運行。這取決於您的具體要求,以及是否有一個事件,您可以利用更好的時機閱讀尺寸。 –