My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until an event triggers a change. So, if you navigate away and then come back, you'll see 3 columns once again. I've tried various approaches in the constructor and other lifecycle hooks, but so far without success. It's possible that I'm not implementing them correctly. The products array of objects, constructor, and ngOnInit() hook in the typescript file are not relevant to this issue. The first image shows how it looks upon loading with 3 columns as default, while the second image displays how it should look after clicking something or resizing the screen. Feel free to provide feedback on the design as well.
<!-- html -->
<div #gridView>
<mat-grid-list cols="{{columnNum}}" gutterSize="5rem" rowHeight="25rem">
<mat-grid-tile *ngFor="let product of products">
<img src="{{ product.image }}" alt="">
</mat-grid-tile>
</mat-grid-list>
</div>
typescript file
import { AfterViewInit, Component, HostListener, OnInit, ViewChild } from '@angular/core';
import { ProductsService } from '../services/products.service';
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit, AfterViewInit {
products : {name: string, productId: string, image: string, price: number, desc: string, size: string, isPrintAvailable: boolean}[] = [];
@ViewChild('gridView') gridView: any;
columnNum = 3; //initial count
tileSize = 450; //one tile width
setColNum(){
let width = this.gridView.nativeElement.offsetWidth;
this.columnNum = Math.trunc(width/this.tileSize);
}
//initial calculation
ngAfterViewInit() {
this.setColNum();
}
//recalculate on window resize
@HostListener('window:resize', ['$event'])
onResize() {
this.setColNum();
}
constructor(private productService: ProductsService) {}
ngOnInit(): void {
this.products = this.productService.getProducts();
}
}
Initial load appearance https://i.sstatic.net/lXDhZ.png
Appearance after triggering an event like a click or screen resize (resets to initial state when navigating away and back) https://i.sstatic.net/7KGuQ.png