Cách tốt nhất để thực hiện một số hành động khi div trong mẫu thay đổi kích thước là gì? Kích thước của div thay đổi khi cửa sổ được thay đổi kích thước. Với Rxjs Observable/đăng ký hoặc là một số cách khác?Cách quan sát khi kích thước phần tử thay đổi trong Angular 2
mẫu:
<div #eMainFrame class="main-frame">
...
</div>
Component:
@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);
}
}
thành phần Cập nhật (ví dụ này phát hiện khi kích thước cửa sổ được thay đổi)
constructor(ngZone: NgZone) {
window.onresize = (e) => {
ngZone.run(() => {
clearTimeout(this.timerWindowResize);
this.timerWindowResize = setTimeout(this._calculateDivSize, 100);
});
}
}
_calculateDivSize(){
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
nhưng điều này mang lại cho tôi một lỗi :
EXCEPTION: Cannot read property 'nativeElement' of undefined
bạn đã thử 'element.resize'? Điều này có thể giúp: http://stackoverflow.com/questions/21170607/angularjs-bind-to-directive-resize – Rajesh