原文再续,书接上一回,上回讲到了“均分列等宽高图像显示(上)”,但是我埋了一个坑,各位看官有没有留意到?
那就是它依赖一个addImage(用于添加的仿按钮图像),如果我没有这个东西,逻辑上是不是就不能用了?是的!那为了使得这个组件能更通用些,改造一下:
旧的html:
<ion-row align-items-center>
<ion-col col-3 align-self-center *ngFor="let item of images, let i = index">
<ion-thumbnail tappable (click)="onViewImages(i)">
<img src="{{item?.originPath}}" class="auto-image" [style.height]="width"/>
</ion-thumbnail>
</ion-col>
<ion-col col-3 align-self-center>
<ion-thumbnail *ngIf="images && images.length<max && canAdd" tappable (click)="onAddImage()">
<img #addImage src="assets/imgs/add.png" class="auto-image"/>
</ion-thumbnail>
</ion-col>
</ion-row>
img都定义变量为#image
,同时移除[style.height]="width"
,变成新的:
<ion-row align-items-center>
<ion-col col-3 align-self-center *ngFor="let item of images, let i = index">
<ion-thumbnail tappable (click)="onViewImages(i)">
<img #image src="{{item?.originPath}}" class="auto-image" />
</ion-thumbnail>
</ion-col>
<ion-col col-3 align-self-center>
<ion-thumbnail *ngIf="images && images.length<max && canAdd" tappable (click)="onAddImage()">
<img #image src="assets/imgs/add.png" class="auto-image"/>
</ion-thumbnail>
</ion-col>
</ion-row>
旧的ts这部分:
width: string;
@ViewChild('addImage') img: ElementRef;
ngAfterViewChecked(){
this.width = this.img.nativeElement.width + 'px';
}
变为新的:
@ViewChildren('image') childCmps: QueryList<ElementRef>;
ngAfterViewChecked(){
if(this.childCmps && this.childCmps.length>0){
this.childCmps.forEach(item =>{
item.nativeElement.height = item.nativeElement.width;
})
}
}
原理很简单,由原来依赖addImage,变为根据自身的宽度调整高度。当然这里我只是以实现为目的的,如想优化那烦请客官自行尝试再告知本人,谢。