I am implementing a mat-grid-list of images and I am changing the number of columns dynamically based on the screen size. This works great except when it first loads it is set to 3 columns regardless of the screen size, until an event happens. So if you navigate to a different component and come back you will once again see 3 columns. I tried adding some code to the constructor or other lifecycle hooks without success but it might just be me not implementing it correctly. On the typescript file, the products array of objects, the constructor, and the ngOnInit() hook are not relevant. The first image is what it looks like when it loads because it defaults to 3 and the second image is what it looks like when I click something or resize the screen, this second image is what it should look like. You will notice that on the typescript file I have the default number of rows set to 3 but if I remove it I get an error. Any feedback on the design is also welcomed.
<!-- 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 should have this width
setColNum(){
let width = this.gridView.nativeElement.offsetWidth;
this.columnNum = Math.trunc(width/this.tileSize);
}
//calculating upon loading
ngAfterViewInit() {
this.setColNum();
}
//recalculating upon browser window resize
@HostListener('window:resize', ['$event'])
onResize() {
this.setColNum();
}
constructor(private productService: ProductsService) {}
ngOnInit(): void {
this.products = this.productService.getProducts();
}
}
what it looks like when it loads

what it looks like after an event like a click or resize the screen (If I navigate away and back it goes back to the top image)
