Angular中使用ResizeObserver监听Html Element宽度变化(支持IE)
1. dependency:
"resize-observer-polyfill": "^1.5.1" ,
2.使用:
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Input,
OnChanges, OnDestroy,
OnInit,
ViewEncapsulation
} from '@angular/core';
import ResizeObserver from 'resize-observer-polyfill';
import {CommonService} from "../services/common.service";
export class ChartComponent implements OnInit {
public normalPCMode: boolean = false;
public smallPCMode: boolean = false;
private resizeObserver: ResizeObserver;
constructor(public common: CommonService, public ref: ChangeDetectorRef) {
}
ngOnInit() {
this.start2ResizeObserver();
}
private start2ResizeObserver() {
let that = this;
this.resizeObserver = new ResizeObserver(() => {
that.resizeContent();
});
this.resizeObserver.observe(document.body);
}
private resizeContent() {
this.smallPCMode = this.common.isSmallPC();
this.normalPCMode = this.common.isNormalPC();
this.ref.markForCheck();
if (this.common.isIE()) {
ChartComponent.handleIEResizeContent();
}
this.ref.detectChanges();
}
private static handleIEResizeContent() {
}
}
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CommonService {
public isMobile() {
return window.innerWidth <= 900;
}
public isSmallPC() {
return window.innerWidth > 900 && window.innerWidth < 1440;
}
public isNormalPC() {
return window.innerWidth >= 1440;
}
public isIE() {
return ((window as any).ActiveXObject || "ActiveXObject" in window);
}
}
3. 注意事项:
**
private start2ResizeObserver() {
let that = this;
this.resizeObserver = new ResizeObserver(() => {
that.resizeContent();
});
this.resizeObserver.observe(document.body);
}
**
let target = document.querySelector('chart');
if (isElement(target)) {
this.resizeObserver.observe(target);
}
**
|