Issue
What I'm trying to accomplish is to display the appropriate view / component based on the device width. I have attached an event listener and created an if statement to render the appropriate ng-template
based on a boolean class flag mobile
, however when I drag my browser the template doesn't change but the resize event does fire...
html
<div class="row dashboard-list-view">
<div class="col-12" *ngIf="mobile; then mobileListBlock else desktopListBlock"></div>
<ng-template #desktopListBlock>
<app-dashboard-list-desktop [data]="data" [filters]="filters"></app-dashboard-list-desktop>
</ng-template>
<ng-template #mobileListBlock>
<app-dashboard-list-mobile [data]="data" [filters]="filters"></app-dashboard-list-mobile>
</ng-template>
</div>
ts
import { Component, Input, OnInit } from '@angular/core';
import { ResizeService } from '../../services/resize.service';
@Component({
selector: 'app-dashboard-list',
templateUrl: './dashboard-list.component.html',
styleUrls: ['./dashboard-list.component.scss']
})
export class DashboardListComponent implements OnInit {
@Input() data: any = [];
@Input() filters: any = [];
mobile: boolean = false;
constructor(private resizeService: ResizeService){}
objectKeys = Object.keys;
ngOnInit() {
this.resizeService.onResize$.subscribe(this.onWindowResize);
this.onWindowResize();
}
onWindowResize() {
console.log("Resize!")
if (window.innerWidth < 992) {
this.mobile = true;
} else {
this.mobile = false;
}
}
}
I've looked for similar questions but I cant figure out what I'm doing wrong here, thank you in advance!
Update
However when I initialize the app on a mobile device it does render the mobile view. Same thing for desktop too. It's just that the event doesn't have any effect after the initial render.
Solution
Well the problem was this line:
this.resizeService.onResize$.subscribe(this.onWindowResize);
changing it to:
this.resizeService.onResize$.subscribe(() => this.onWindowResize());
did the trick. It prolly had to do with the this
context on the member function. No idea why no error was thrown tho...
Answered By - 0x_Anakin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.