I am trying to build an angular component which displays an image based on the src, width and height provided by the parent element.
This is my code:
my-image-logo.component.html
<img #imgDiv src="{{name}}" >
my-image-logo.component.ts
export class MyImageLogoComponent implements OnInit {
@Input() name;
@Input() width = "100px";
@Input() height = "100px";
@ViewChild("imgDiv") imgDiv: ElementRef;
constructor() { }
ngOnInit() {
this.imgDiv.nativeElement.setAttribute("width", this.width);
this.imgDiv.nativeElement.setAttribute("height", this.height);
}
}
parent-component.html
<app-my-image-logo [name]="userDetails.profilePic" [width]="'50px;'" [height]="'50px;'"></app-my-image-logo>
This works perfectly, but I was trying to not initialize the width and height in ngOnInit, instead use ngStyle as follows:
<img [ngStyle]="{'width': width, 'height': height}" src="{{name}}" >
But this is not working. I even tried the following, but even that doesn't work:
<img width="{{width}}" height="{{height}}" src="{{name}}" >
What am I doing wrong? Also, is this the right way to assign css styles for the components?
<app-my-image-logo [width]="'50px'" [height]="'50px'" ...>(without the;). See this stackblitz.width="0" height="0"[width]="width" [height]="height".