Angular 4를 사용하여 창 크기 감지
반응 형 내비게이션 바를 만들려고했고 미디어 쿼리를 사용하고 싶지 않으므로 *ngIF
창 크기를 기준으로 사용하려고합니다 . 그러나 Angular 4 창 크기 감지에 대한 방법이나 문서를 찾을 수 없기 때문에 문제가 발생했습니다. JavaScript 방법도 시도했지만 지원되지 않습니다.
또한 다음을 시도했습니다 .
constructor(platform: Platform) {
platform.ready().then((readySource) => {
console.log('Width: ' + platform.width());
console.log('Height: ' + platform.height());
});
}
... 이온 계에 사용되었습니다.
그리고 screen.availHeight
, 그러나 여전히 성공하지 못했습니다.
init에서 얻으려면
public innerWidth: any;
ngOnInit() {
this.innerWidth = window.innerWidth;
}
크기 조정시 업데이트를 유지하려면 다음을 수행하십시오.
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
특정 중단 점에 대해 반응하려면 (예 : 너비가 768px 미만인 경우 수행) BreakpointObserver를 사용할 수도 있습니다.
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
{ ... }
const isSmallScreen = breakpointObserver.isMatched('(max-width: 599px)');
또는 중단 점의 변경 사항을 들어도됩니다.
breakpointObserver.observe([
'(max-width: 768px)'
]).subscribe(result => {
if (result.matches) {
doSomething();
} else {
// if necessary:
doSomethingElse();
}
});
Platform
width()
및 height()
에 대한 문서에는 이러한 메서드가 각각 window.innerWidth
및을 사용한다고 명시 되어 window.innerHeight
있습니다. 그러나 차원이 캐시 된 값이기 때문에 메서드를 사용하는 것이 선호되어 여러 번의 값 비싼 DOM 읽기 기회를 줄입니다.
import { Platform } from 'ionic-angular';
...
private width:number;
private height:number;
constructor(private platform: Platform){
platform.ready().then(() => {
this.width = platform.width();
this.height = platform.height();
});
}
구성 요소를 쉽게 테스트 할 수 있도록하려면 Angular 서비스에서 전역 창 개체를 래핑해야합니다.
import { Injectable } from '@angular/core';
@Injectable()
export class WindowService {
get windowRef() {
return window;
}
}
그런 다음 다른 서비스처럼 삽입 할 수 있습니다.
constructor(
private windowService: WindowService
) { }
그리고 소비 ...
ngOnInit() {
const width= this.windowService.windowRef.innerWidth;
}
당신이 사용할 수있는 https://github.com/ManuCutillas/ng2-responsive 이 도움이 희망 :-)
참고 URL : https://stackoverflow.com/questions/45350716/detect-window-size-using-angular-4
'developer tip' 카테고리의 다른 글
다 대다 필드를위한 Django ModelForm (0) | 2020.10.29 |
---|---|
앱이 내 뷰의 백그라운드로 들어갈 때를 감지하는 가장 좋은 방법은 무엇입니까? (0) | 2020.10.28 |
조건에서 할당 할 수 있습니까? (0) | 2020.10.28 |
테이블 표시, redshift에서 동등한 테이블 설명 (0) | 2020.10.28 |
SEGV_MAPERR은 무엇입니까? (0) | 2020.10.28 |