我正在尝试使用ngStyle将高度和宽度样式添加到img元素:
<img class="image-full-view" [ngStyle]="{'height': selectedImage.heightSize, 'width': selectedImage.widthSize}" [src]="selectedImage.imagePath" alt="Man Praying">
图像信息来自在服务文件中创建的对象:
private images = [
new Image('Man Praying', 1, 'Cambodia', 'Man praying to Sun', '£100', '../../assets/Images/Cambodia/Praying to the Sun.JPG', '250px', '800px'),
]
高度为250像素,宽度为800像素。
这是在单独的模型文件中创建对象构造函数的位置:
export class Image {
public name: string;
public id: number;
public album: string;
public description: string;
public price: any;
public imagePath: string;
public heightSize: any;
public widthSize: any;
constructor(name: string, id: number, album: string, description: string, price: any, imagePath: string, heightSize: any, widthSize: any) {
this.name = name;
this.id = id;
this.album = album;
this.description = description;
this.price = price;
this.imagePath = imagePath;
this.heightSize = heightSize;
this.widthSize = widthSize;
}
}
图像高度已正确应用于元素,但宽度未正确。我已经通过使用Chrome开发工具检查元素来确认了这一点。因为似乎看不到问题在哪里,我在这里缺少什么吗?
这是chrome开发工具中元素的显示方式:
<img _ngcontent-vxx-c18="" alt="Man Praying" class="image-full-view" ng-reflect-ng-style="[object Object]" src="../../assets/Images/Cambodia/Praying to the Sun.JPG" style="height: 250px;">
我已经检查了所有代码,以确保未在另一个样式表中设置图像宽度。
要使用多个ngStyle,您可以添加一个返回它的方法:
HTML:
[ngStyle]="imageStyle()"
TS:
imageStyle(): object {
return {
height: this.image.heightSize ? this.image.heightSize : '',
width: this.image.widthSize ? this.image.widthSize : ''
};
}
似乎对象构造函数中的分号是问题:
export class Image {
public name: string;
public id: number;
public album: string;
public description: string;
public price: any;
public imagePath: string;
public heightSize: any;
public widthSize: any
constructor(name: string, id: number, album: string, description: string, price: any, imagePath: string, heightSize: any, widthSize: any) {
this.name = name;
this.id = id;
this.album = album;
this.description = description;
this.price = price;
this.imagePath = imagePath;
this.heightSize = heightSize;
this.widthSize = widthSize;
}
}
有布莱恩推荐:
export class Image {
constructor(
public name: string,
public id: number,
public album: string,
public description: string,
public price: any,
public imagePath: string,
public heightSize: any,
public widthSize: any) {}
}
愚蠢的错误!