I have a SPA that ultimately lists out a lot of data, but in batches.
I created a component at the bottom of the list, with a 'Visibility' directive so that when it is visible we make a new request to the dataset in a SQL server to get the next batch.
html-tag-for-component
<app-infinity-scroll
[(pageNumber)]="page"
[displayPage]="displayPage"
[authd]="authd"
[done]="done"
[numResults]="displayPage == 'tiles-hub' ? hubs.length : wallets.length"
class="{{scrollVisible ? '' : 'hiddenDisplay'}}"
trackVisibility
></app-infinity-scroll>
component-to-trigger-data-call
import { outputAst } from '#angular/compiler';
import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '#angular/core';
import { DbSqlService } from 'services/db-sql.service';
import { TokenAuthService } from 'services/token-auth.service';
import { TrackVisibilityDirective } from 'src/app/directives/track-visibility.directive';
import { SortStyle } from 'src/app/interfaces/mvlot';
import { MatProgressBar } from '#angular/material/progress-bar';
#Component({
selector: 'app-infinity-scroll',
templateUrl: './infinity-scroll.component.html',
styleUrls: ['./infinity-scroll.component.scss']
})
export class InfinityScrollComponent implements OnInit {
#Input() pageNumber: number;
#Input() displayPage: string;
#Input() authd: boolean;
#Input() done: boolean;
#Input() numResults: number;
#Output() pageNumberChange = new EventEmitter<number>();
lastDisplay = '';
loading: boolean = true;
constructor(
private visTrack: TrackVisibilityDirective
, private cdr: ChangeDetectorRef
, private dbApi: DbSqlService
, private authService: TokenAuthService
) {
}
ngOnInit(): void {
this.authService.UserAuthd.subscribe((res) => {
// if (res) {
this.dbApi.initGetWalletsHandler(0, 50, SortStyle.scoreDesc);
this.pageNumber = 1;
// }
})
this.visTrack.visibile.subscribe((val) => {
if (!this.done) {
this.loading = true;
if (val) {
if (this.displayPage == 'tiles') {
this.dbApi.initGetWalletsHandler((this.pageNumber) * 50, 50, SortStyle.default);
this.pageNumber += 1;
}
if (this.displayPage == 'tiles-hub') {
this.dbApi.initGetHubsHandler((this.pageNumber) * 50, 50);
this.pageNumber += 1;
}
}
}
})
}
}
Some functions run, call out to a back-end, respond with data, where a listener is waiting.
this.dbApi.resultObs.subscribe(val => {
if (val.append != true) {
this.results = [];
}
if (val.reset) {
this.page = 1;
}
val.data.data.forEach((b: any) => {
var result: Collection;
var existingResults = this.results.filter(w => w.ownerId == b.ownerId);
if (existingResults.length == 0) {
result = {
ownerId: b.ownerId
, totalScore: b.modifiedLandScore
, filteredCount: b.filteredCount
, totalLots: b.totalLots
, totalPrice: b.totalPrice
, name: ''
, lands: []
, type: CollectionType.b
}
result.bs.push(b);
this.results.push(result);
} else {
result = existingResults[0];
result.bs.push(b);
}
});
this.resultDataSource = new MatTableDataSource(this.results);
this.collectionType = CollectionType.b;
this.uiService.loadingBar(false);
this.done = val.data.data.length == 0;
this.cdr.detectChanges();
})
And, finally this is laid out for the user:
<tr *ngFor="let result of results">
<td>
<display-block
[collection]="b"
[displayVertical]="displayVertical"
[displayCaseCount]="displayCaseCount"
[gridClassName]="gridClassName"
[authd]="authd"
[type]="result.type"
[expanded]="results.length == 1"
[isPhonePortrait]="isPhonePortrait"
></display-block>
</td>
</tr>
Everything works fine on the first grab of data.
And everything appears to work fine on the second pull, but for any of the items appended to the view with the second pull, ChangeDetector just seems to give up. I'll trigger an action, that should modify the view, but nothing happens, unless I manully put in cdr, or I flip to a new window, or something, then they respond.
I'm going to continue trying to find a root cause, but at the moment, I'm out of ideas. There's no prominent error message that would imply something broke. The items fromt the first batch still work. But the ones from the second will appear to lock up. until CDR is forced by an outside event.
I wanted to check here to see if anyone had any ideas on what may be causing this.
Also, here's the declaration code for 'trackVisibility'
import {
Directive,
ElementRef,
EventEmitter,
NgZone,
OnDestroy,
OnInit,
Output,
} from '#angular/core';
#Directive({
selector: '[trackVisibility]',
})
export class TrackVisibilityDirective implements OnInit, OnDestroy {
observer!: IntersectionObserver;
#Output()
visibile = new EventEmitter<boolean>();
constructor(private el: ElementRef<HTMLElement>, private ngZone: NgZone) {}
ngOnInit(): void {
this.ngZone.runOutsideAngular(() => {
this.observer = new IntersectionObserver((entries) => {
entries.forEach((e) => {
this.visibile.emit(e.isIntersecting);
});
});
this.observer.observe(this.el.nativeElement);
});
}
ngOnDestroy(): void {
this.observer.disconnect();
}
}
here is the solution
You used runOutsideAngular function in your Directive.
"Running functions via runOutsideAngular allows you to escape Angular's zone and do work that doesn't trigger Angular change-detection or is subject to Angular's error handling. Any future tasks or microtasks scheduled from within this function will continue executing from outside of the Angular zone."
I also changed some parts of the code for more readability.
I got problem with angular component.
When I make my component with selector, it works as expected: execute httpget, and render photo with title.
But in console I got two errors:
ERROR TypeError: "_co.photo is undefined"
View_PhotoHolderComponent_0 PhotoHolderComponent.html:2
and
ERROR CONTEXT
...
PhotoHolderComponent.html:2:8
View_PhotoHolderComponent_0 PhotoHolderComponent.html:2
I got html:
<div class="photo-holder">
<h2>{{photo.title}}</h2>
<img src="{{photo.url}}">
</div>
and ts:
import { Component, OnInit } from '#angular/core';
import { Photo } from './photo'
import { PhotoDeliveryService } from '../photo-delivery-service.service'
#Component({
selector: 'app-photo-holder',
templateUrl: './photo-holder.component.html',
styleUrls: ['./photo-holder.component.css']
})
export class PhotoHolderComponent implements OnInit {
photo:Photo
constructor( private photoService : PhotoDeliveryService) {
}
ngOnInit() {
this.photoService.getRandomPhoto().subscribe((data: Photo) => this.photo = {...data})
}
}
and service :
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Photo } from './photo-holder/photo'
#Injectable({
providedIn: 'root'
})
export class PhotoDeliveryService {
value : Number
url : string
constructor(private http: HttpClient) {
this.url = "https://jsonplaceholder.typicode.com/photos/";
this.value = Math.floor(Math.random() * 10) + 1;
}
getRandomPhoto() {
return this.http.get<Photo>(this.getUrl())
}
getUrl(){
return this.url + this.value;
}
}
I suspect that could be made by binding property before query results was returned.
How can I rid off this problem, can I wait for this query, or this is different kind of problem ?
You are getting the error because before your service could resolve, the template bindings are resolved and at that time photo object is undefined.
first thing, you can initialize the photo object but then you might have to detect the changes using ChangeDetectorRef to reflect the value returned by the service.
photo:Photo = {
title:'',
url:''
};
constructor( private photoService : PhotoserviceService, private cdr:ChangeDetectorRef) {
}
ngOnInit() {
this.photoService.getRandomPhoto().subscribe((data: Photo) => {
this.photo = data;
this.cdr.detectChanges();
});
}
I have already done the project using simple java script. Now Its revamping as SPA using Angular.
Now I'm stucked to do the same using Angular.
Functionality:
Click the button to disable and append in particular div and if button clicks inside appended div then previously disabled button to be enabled.
That's it.
I have done other than to enable disabled button:
Problem is pBtn not available in ElementRef
Below is my code and stackblitz link:
Hope someone could help in this.
import { Component, OnInit, DoCheck, AfterViewInit, ViewChild, ElementRef,Renderer2 } from '#angular/core';
import { Interviewcreate } from '../../shared/interview-create';
import { Interview } from '../../shared/interview';
import { DataService } from '../../data-service';
import { Router } from '#angular/router';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Component({
selector: 'dashboard-component',
templateUrl: './dashboard-component.html',
styleUrls: [ './dashboard-component.css' ]
})
export class DashboardComponent implements OnInit, DoCheck, AfterViewInit, OnChanges {
users: Interviewcreate;
#ViewChild('answerbox') div:ElementRef;
#ViewChild('htmlToAdd') htmlToAdd:ElementRef;
#ViewChild('questionbox') questionbox:ElementRef;
question1 = ['<p>', '</p>', 'Polar bears live in the north pole']
constructor(private service: DataService,
private router: Router,
private http:HttpClient,
private renderer: Renderer2,
private el:ElementRef
){
}
ngOnInit(){
}
ngDoCheck(){
if(this.htmlToAdd.nativeElement.children.length>0){
Array.prototype.forEach.call(this.htmlToAdd.nativeElement.children, (element) => {
//console.log(element)
element.addEventListener('click', (e)=>{
this.resultview()
console.log(e)
e.target.remove()
})
});
}
}
ngAfterViewInit() {
let sss = this.el.nativeElement.querySelector('.dotted-box > button')
//.addEventListener('click', this.onClick.bind(this));
}
onClick(event) {
console.log(event);
}
getvalue(e){
const li = this.renderer.createElement('button');
const text = this.renderer.createText(e.target.textContent);
this.renderer.appendChild(li, text);
this.renderer.appendChild(this.htmlToAdd.nativeElement, li);
setTimeout(
()=>{
this.resultview()
}
,100)
e.target.disabled = true;
Array.prototype.forEach.call(this.htmlToAdd.nativeElement.children, (element) => {
this.renderer.addClass(element, 'btn');
this.renderer.addClass(element, 'btn-outline-primary');
});
}
resultview() {
this.div.nativeElement.innerHTML = this.htmlToAdd.nativeElement.textContent.trim();
}
}
Try out this, you had written some hard logic.
Push appending value will solve your problem.
export class DashboardComponent {
#ViewChild('answerbox') div:ElementRef;
#ViewChild('htmlToAdd') htmlToAdd:ElementRef;
#ViewChild('questionbox') questionbox:ElementRef;
question1 = ['<p>', '</p>', 'Polar bears live in the north pole' ]
questionboxvalue = [];
#Output() someEvent = new EventEmitter<string>();
constructor(private service: DataService,
private router: Router,
private http:HttpClient,
private renderer: Renderer2,
private el:ElementRef
){
}
onClick(event) {
console.log(event);
}
getvalue(e){
this.questionboxvalue.push({index: e.target.dataset.index, value: e.target.textContent.trim()})
e.target.disabled = true;
this.resultview();
}
getbvalue(event) {
this.someEvent.next(event);
Array.prototype.forEach.call(this.el.nativeElement.querySelectorAll('.shadowbutton'), (element, i)=>{
if(element.dataset.index === event.target.dataset.index) {
element.disabled = false;
this.questionboxvalue = this.questionboxvalue.filter((val)=>{
return val.index !== event.target.dataset.index;
})
this.resultview()
}
})
}
resultview() {
setTimeout(()=>{
this.div.nativeElement.innerHTML = this.htmlToAdd.nativeElement.textContent.trim();
}, 100)
}
}
I would like to perform some tasks based on the window re-size event (on load and dynamically).
Currently I have my DOM as follows:
<div id="Harbour">
<div id="Port" (window:resize)="onResize($event)" >
<router-outlet></router-outlet>
</div>
</div>
The event correctly fires
export class AppComponent {
onResize(event) {
console.log(event);
}
}
How do I retrieve the Width and Height from this event object?
Thanks.
<div (window:resize)="onResize($event)"
onResize(event) {
event.target.innerWidth;
}
or using the HostListener decorator:
#HostListener('window:resize', ['$event'])
onResize(event) {
event.target.innerWidth;
}
Supported global targets are window, document, and body.
Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.
I know this was asked a long time ago, but there is a better way to do this now! I'm not sure if anyone will see this answer though. Obviously your imports:
import { fromEvent, Observable, Subscription } from "rxjs";
Then in your component:
resizeObservable$: Observable<Event>
resizeSubscription$: Subscription
ngOnInit() {
this.resizeObservable$ = fromEvent(window, 'resize')
this.resizeSubscription$ = this.resizeObservable$.subscribe( evt => {
console.log('event: ', evt)
})
}
Then be sure to unsubscribe on destroy!
ngOnDestroy() {
this.resizeSubscription$.unsubscribe()
}
#Günter's answer is correct. I just wanted to propose yet another method.
You could also add the host-binding inside the #Component()-decorator. You can put the event and desired function call in the host-metadata-property like so:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
host: {
'(window:resize)': 'onResize($event)'
}
})
export class AppComponent{
onResize(event){
event.target.innerWidth; // window width
}
}
The correct way to do this is to utilize the EventManager class to bind the event. This allows your code to work in alternative platforms, for example server side rendering with Angular Universal.
import { EventManager } from '#angular/platform-browser';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { Injectable } from '#angular/core';
#Injectable()
export class ResizeService {
get onResize$(): Observable<Window> {
return this.resizeSubject.asObservable();
}
private resizeSubject: Subject<Window>;
constructor(private eventManager: EventManager) {
this.resizeSubject = new Subject();
this.eventManager.addGlobalEventListener('window', 'resize', this.onResize.bind(this));
}
private onResize(event: UIEvent) {
this.resizeSubject.next(<Window>event.target);
}
}
Usage in a component is as simple as adding this service as a provider to your app.module and then importing it in the constructor of a component.
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-component',
template: ``,
styles: [``]
})
export class MyComponent implements OnInit {
private resizeSubscription: Subscription;
constructor(private resizeService: ResizeService) { }
ngOnInit() {
this.resizeSubscription = this.resizeService.onResize$
.subscribe(size => console.log(size));
}
ngOnDestroy() {
if (this.resizeSubscription) {
this.resizeSubscription.unsubscribe();
}
}
}
There's a ViewportRuler service in angular CDK. It runs outside of the zone, supports orientationchange and resize. It works with server side rendering too.
#Component({
selector: 'my-app',
template: `
<p>Viewport size: {{ width }} x {{ height }}</p>
`
})
export class AppComponent implements OnDestroy {
width: number;
height: number;
private readonly viewportChange = this.viewportRuler
.change(200)
.subscribe(() => this.ngZone.run(() => this.setSize()));
constructor(
private readonly viewportRuler: ViewportRuler,
private readonly ngZone: NgZone
) {
// Change happens well, on change. The first load is not a change, so we init the values here. (You can use `startWith` operator too.)
this.setSize();
}
// Never forget to unsubscribe!
ngOnDestroy() {
this.viewportChange.unsubscribe();
}
private setSize() {
const { width, height } = this.viewportRuler.getViewportSize();
this.width = width;
this.height = height;
}
}
Stackblitz example for ViewportRuler
The benefit is, that it limits change detection cycles (it will trigger only when you run the callback in the zone), while (window:resize) will trigger change detection every time it gets called.
Here is a better way to do it. Based on Birowsky's answer.
Step 1: Create an angular service with RxJS Observables.
import { Injectable } from '#angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
#Injectable()
export class WindowService {
height$: Observable<number>;
//create more Observables as and when needed for various properties
hello: string = "Hello";
constructor() {
let windowSize$ = new BehaviorSubject(getWindowSize());
this.height$ = (windowSize$.pluck('height') as Observable<number>).distinctUntilChanged();
Observable.fromEvent(window, 'resize')
.map(getWindowSize)
.subscribe(windowSize$);
}
}
function getWindowSize() {
return {
height: window.innerHeight
//you can sense other parameters here
};
};
Step 2: Inject the above service and subscribe to any of the Observables created within the service wherever you would like to receive the window resize event.
import { Component } from '#angular/core';
//import service
import { WindowService } from '../Services/window.service';
#Component({
selector: 'pm-app',
templateUrl: './componentTemplates/app.component.html',
providers: [WindowService]
})
export class AppComponent {
constructor(private windowService: WindowService) {
//subscribe to the window resize event
windowService.height$.subscribe((value:any) => {
//Do whatever you want with the value.
//You can also subscribe to other observables of the service
});
}
}
A sound understanding of Reactive Programming will always help in overcoming difficult problems. Hope this helps someone.
I haven't seen anyone talking about MediaMatcher of angular/cdk.
You can define a MediaQuery and attach a listener to it - then anywhere on your template (or ts) you can invoke stuff if the Matcher is matched.
LiveExample
App.Component.ts
import {Component, ChangeDetectorRef} from '#angular/core';
import {MediaMatcher} from '#angular/cdk/layout';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
mobileQuery: MediaQueryList;
constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher) {
this.mobileQuery = media.matchMedia('(max-width: 600px)');
this._mobileQueryListener = () => changeDetectorRef.detectChanges();
this.mobileQuery.addListener(this._mobileQueryListener);
}
private _mobileQueryListener: () => void;
ngOnDestroy() {
this.mobileQuery.removeListener(this._mobileQueryListener);
}
}
App.Component.Html
<div [class]="mobileQuery.matches ? 'text-red' : 'text-blue'"> I turn red on mobile mode
</div>
App.Component.css
.text-red {
color: red;
}
.text-blue {
color: blue;
}
source: https://material.angular.io/components/sidenav/overview
Assuming that < 600px means mobile to you, you can use this observable and subscribe to it:
First we need the current window size. So we create an observable which only emits a single value: the current window size.
initial$ = Observable.of(window.innerWidth > 599 ? false : true);
Then we need to create another observable, so that we know when the window size was changed. For this we can use the "fromEvent" operator. To learn more about rxjs`s operators please visit: rxjs
resize$ = Observable.fromEvent(window, 'resize').map((event: any) => {
return event.target.innerWidth > 599 ? false : true;
});
Merg these two streams to receive our observable:
mobile$ = Observable.merge(this.resize$, this.initial$).distinctUntilChanged();
Now you can subscribe to it like this:
mobile$.subscribe((event) => { console.log(event); });
Remember to unsubscribe :)
I checked most of these answers. then decided to check out Angular documentation on Layout.
Angular has its own Observer for detecting different sizes and it is easy to implement into the component or a Service.
a simpl example would be:
import {BreakpointObserver, Breakpoints} from '#angular/cdk/layout';
#Component({...})
class MyComponent {
constructor(breakpointObserver: BreakpointObserver) {
breakpointObserver.observe([
Breakpoints.HandsetLandscape,
Breakpoints.HandsetPortrait
]).subscribe(result => {
if (result.matches) {
this.activateHandsetLayout();
}
});
}
}
hope it helps
If you want just one event after the resize is finished, it's better to use RxJS with debounceTime :
debounceTime: Discard emitted values that take less than the specified time between output.
He waits > 0.5s between 2 events emitted before running the code.
In simpler terms, it waits for the resizing to be finished before executing the next code.
// RxJS v6+
import { fromEvent } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';
...
const resize$ = fromEvent(window, 'resize');
resize$
.pipe(
map((i: any) => i),
debounceTime(500) // He waits > 0.5s between 2 events emitted before running the next.
)
.subscribe((event) => {
console.log('resize is finished');
});
StackBlitz
Based on the solution of #cgatian I would suggest the following simplification:
import { EventManager } from '#angular/platform-browser';
import { Injectable, EventEmitter } from '#angular/core';
#Injectable()
export class ResizeService {
public onResize$ = new EventEmitter<{ width: number; height: number; }>();
constructor(eventManager: EventManager) {
eventManager.addGlobalEventListener('window', 'resize',
e => this.onResize$.emit({
width: e.target.innerWidth,
height: e.target.innerHeight
}));
}
}
Usage:
import { Component } from '#angular/core';
import { ResizeService } from './resize-service';
#Component({
selector: 'my-component',
template: `{{ rs.onResize$ | async | json }}`
})
export class MyComponent {
constructor(private rs: ResizeService) { }
}
This is not exactly answer for the question but it can help somebody who needs to detect size changes on any element.
I have created a library that adds resized event to any element - Angular Resize Event.
It internally uses ResizeSensor from CSS Element Queries.
Example usage
HTML
<div (resized)="onResized($event)"></div>
TypeScript
#Component({...})
class MyComponent {
width: number;
height: number;
onResized(event: ResizedEvent): void {
this.width = event.newWidth;
this.height = event.newHeight;
}
}
I wrote this lib to find once component boundary size change (resize) in Angular, may this help other people. You may put it on the root component, will do the same thing as window resize.
Step 1: Import the module
import { BoundSensorModule } from 'angular-bound-sensor';
#NgModule({
(...)
imports: [
BoundSensorModule,
],
})
export class AppModule { }
Step 2: Add the directive like below
<simple-component boundSensor></simple-component>
Step 3: Receive the boundary size details
import { HostListener } from '#angular/core';
#Component({
selector: 'simple-component'
(...)
})
class SimpleComponent {
#HostListener('resize', ['$event'])
onResize(event) {
console.log(event.detail);
}
}
Below code lets observe any size change for any given div in Angular.
<div #observed-div>
</div>
then in the Component:
oldWidth = 0;
oldHeight = 0;
#ViewChild('observed-div') myDiv: ElementRef;
ngAfterViewChecked() {
const newWidth = this.myDiv.nativeElement.offsetWidth;
const newHeight = this.myDiv.nativeElement.offsetHeight;
if (this.oldWidth !== newWidth || this.oldHeight !== newHeight)
console.log('resized!');
this.oldWidth = newWidth;
this.oldHeight = newHeight;
}
On Angular2 (2.1.0) I use ngZone to capture the screen change event.
Take a look on the example:
import { Component, NgZone } from '#angular/core';//import ngZone library
...
//capture screen changed inside constructor
constructor(private ngZone: NgZone) {
window.onresize = (e) =>
{
ngZone.run(() => {
console.log(window.innerWidth);
console.log(window.innerHeight);
});
};
}
I hope this help!
Here is an update to #GiridharKamik answer above with the latest version of Rxjs.
import { Injectable } from '#angular/core';
import { Observable, BehaviorSubject, fromEvent } from 'rxjs';
import { pluck, distinctUntilChanged, map } from 'rxjs/operators';
#Injectable()
export class WindowService {
height$: Observable<number>;
constructor() {
const windowSize$ = new BehaviorSubject(getWindowSize());
this.height$ = windowSize$.pipe(pluck('height'), distinctUntilChanged());
fromEvent(window, 'resize').pipe(map(getWindowSize))
.subscribe(windowSize$);
}
}
function getWindowSize() {
return {
height: window.innerHeight
//you can sense other parameters here
};
};
Here is a simple and clean solution I created so I could inject it into multiple components.
ResizeService.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ResizeService {
constructor() {
window.addEventListener('resize', (e) => {
this.onResize.next();
});
}
public onResize = new Subject();
}
In use:
constructor(
private resizeService: ResizeService
) {
this.subscriptions.push(this.resizeService.onResize.subscribe(() => {
// Do stuff
}));
}
private subscriptions: Subscription[] = [];
What I did is as follows, much like what Johannes Hoppe suggested:
import { EventManager } from '#angular/platform-browser';
import { Injectable, EventEmitter } from '#angular/core';
#Injectable()
export class ResizeService {
public onResize$ = new EventEmitter<{ width: number; height: number; }>();
constructor(eventManager: EventManager) {
eventManager.addGlobalEventListener('window', 'resize',
event => this.onResize$.emit({
width: event.target.innerWidth,
height: event.target.innerHeight
}));
}
getWindowSize(){
this.onResize$.emit({
width: window.innerWidth,
height: window.innerHeight
});
}
}
In app.component.ts:
Import { ResizeService } from ".shared/services/resize.service"
import { Component } from "#angular/core"
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent{
windowSize: {width: number, height: number};
constructor(private resizeService: ResizeService){
}
ngOnInit(){
this.resizeService.onResize$.subscribe((value) => {
this.windowSize = value;
});
this.resizeService.getWindowSize();
}
}
Then in your app.component.html:
<router-outlet *ngIf = "windowSize?.width > 1280 && windowSize?.height > 700; else errorComponent">
</router-outlet>
<ng-template #errorComponent>
<app-error-component></app-error-component>
</ng-template>
Another approach that I took was
import {Component, OnInit} from '#angular/core';
import {fromEvent} from "rxjs";
import {debounceTime, map, startWith} from "rxjs/operators";
function windowSizeObserver(dTime = 300) {
return fromEvent(window, 'resize').pipe(
debounceTime(dTime),
map(event => {
const window = event.target as Window;
return {width: window.innerWidth, height: window.innerHeight}
}),
startWith({width: window.innerWidth, height: window.innerHeight})
);
}
#Component({
selector: 'app-root',
template: `
<h2>Window Size</h2>
<div>
<span>Height: {{(windowSize$ | async)?.height}}</span>
<span>Width: {{(windowSize$ | async)?.width}}</span>
</div>
`
})
export class WindowSizeTestComponent {
windowSize$ = windowSizeObserver();
}
here the windowSizeObserver can be reused in any component