【发布时间】:2021-05-28 07:30:11
【问题描述】:
我正在实现一个 mat-grid-list 图像,并且我正在根据屏幕大小动态更改列数。这很好用,除非当它第一次加载时它被设置为 3 列而不管屏幕大小,直到事件发生。因此,如果您导航到不同的组件并返回,您将再次看到 3 列。 我尝试向构造函数或其他生命周期钩子添加一些代码但没有成功,但这可能只是我没有正确实现它。在 typescript 文件中,products 对象数组、构造函数和 ngOnInit() 钩子不相关。第一张图片是它加载时的样子,因为它默认为 3,第二张图片是我点击某些东西或调整屏幕大小时的样子,第二张图片就是它应该看起来的样子。您会注意到,在打字稿文件中,我将默认行数设置为 3,但如果我将其删除,则会出现错误。也欢迎对设计提出任何反馈。
<!-- 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>
打字稿文件
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();
}
}
【问题讨论】:
标签: javascript css angular typescript angular-material