简体   繁体   中英

Angular - Property Binding for height & width not working for Image

I am trying to make an example of property binding in Angular. I decided to take an image and then put all 3 attributes of it -- width, height, src by property binding. To my surprise, though there was no error, and image is being rendered by URL (no error in url) but still the width and height are being rendered as zero (0). Why this? As far as I know Image takes height and width as its properties. Then where is the problem?

abc.component.html

//This does not work - gives height:0px, width:0px
<img [width]="'100px'" [height]="'100px'" [src]="'./assets/img/hermione.jpg'">

//This works - renders image, with height:100px, width: 100px
<img width="100px" height="100px" [src]="'./assets/img/hermione.jpg'">

Can someone explain by the strange behavior of why the second scenario runs well, but in first though images gets rendered but never seen (as height:0px, width:0px)?

Error:

在此处输入图像描述

Also, (as per Pronoy Sarkar - see answer below)

//This also works
<img [attr.width]="'100px'" [attr.height]="'100px'" [src]="'./assets/img/hermione.jpg'">

Now, question is why simple [height] and [width] does not work? Afterall, we never did [attr.src] ?

试试[attr.width][attr.height]

If you have a look at the Attribute List here on HTML attribute reference - Attribute List Page on MDN , it says that width and height are attributes and NOT Native Properties .

If you then go over to Attribute Binding section of Template Syntax Fundamentals Section, it states that:

As the message says, the element does not have a colspan property. It has the "colspan" attribute, but interpolation and property binding can set only properties, not attributes.

You need attribute bindings to create and bind to such attributes.

On the similar lines, width and height aren't Native Properties of an img tag. They are attributes.

Hence you can't set width and height using the property binding syntax( [width] / [height] ). You'll have to use the Attribute Binding Syntax instead.

PS: src was also present in the Attribute List Page on MDN page. But since in the description, there wasn't a mention of it as a property, I figured it was a native property.

You can use Attribute binding for html attribute :

[attr.width]="'100px'"
[attr.height]="'100px'"

or

[attr.width.px]="widthProp"
[attr.height.px]="heightProp"

or

[attr.width.%]="widthProp"
[attr.height.%]="heightProp"

or you can use Styling binding for css style :

[style.width]="'100px'"
[style.height]="'100px'"

or

[style.width.px]="widthProp"
[style.height.px]="heightProp"

or

[style.width.%]="widthProp"
[style.height.%]="heightProp"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM