Reputation: 1042
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?
Upvotes: 0
Views: 1046
Reputation: 316
imgDiv might be undefined when we try to access in ngOnInit. Try to do that inside ngAfterViewInit, but I am not sure whether we can change the width because the view already got drawn
Upvotes: 0
Reputation: 735
You can modify attributes by doing this (in your child component):
<img [attr.width]="width" [attr.height]="height">
Upvotes: 1
Reputation: 2567
In your child component, you will have to change the HTML to
<img [width]="width" [height]="height" [src]="name" >
Upvotes: 0
Reputation: 2756
Your can share the parent's css file with a child with :
@Component({
selector: 'lions',
templateUrl: 'lions.component.html',
styleUrls: ['lions.component.css', '../zoo.component.css']
})
(zoo is the parent, lion the child)
But in your case I would just set the child width and height to 100%, for exemple in lion.css :
:host() { width: 100%; height: 100% }
( :host()
means the root tag of your component )
Upvotes: 0