I’m starting on Angular and Typescript and I’m currently stumbling on a problem, so I’m looking for some guidance
I want to improve the speed of my site by displaying only images in webp format. However, some browsers don’t seem to support it
That’s why I use the <picture>
tag to provide an alternative if the browser doesn’t support the webp format contained in <source>
. If it fails, it will then load the jpg image present in <image>
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.png" alt="" title=""/>
</picture>
I would like to implement a class and an *ngIf
condition to render the image only if a certain variable exists. But I don’t understand where I’m supposed to apply this? In the <picture>
tag, in the <source>
tag, or in the <img>
tag?
Also, where should I place the alt and title attributes? In the <img>
tag?
Thank you in advance for your answer
2
Answers
Though what you are trying to achieve is not clear but let me try to explain all the scenarios. Usually if the picture tag looks like that it means that the browser will try to load the webp image initially and if it fails it will load the image tag inside the picture.
So now lets discuss about applying ngIf condition. There are 3 possibilities and I will explain the situation
As far is class or style property is concerned it can be applied on any of the tag. If applied on the picture tag that style is applicable to the container of the source tag. If you want to individually style each of the source tag you can do so by applying it specifically on the source tag. In most of the case applying style on the picture tag is what is needed.
Regarding alt and title attributes, title attribute can be placed on both source and img tag. But it makes sense to place the alt attribute in the img tag since that is the ultimate fall back image and if that can’t be rendered the alt text will be displayed
Here is an sample implementation if you want to play with.
Please mark it as answer if it helps. Happy Coding 🙂
img
element.src
attribute of theimg
element to the source of the image that needs to be displayed.*ngIf
directive to theimg
element to check if the image should be displayed or not.img
element, one for when the image is displayed and one for when it is hidden.*ngIf
directive to theimg
element.Here’s the code:
Note: In the code above,
imageSource
andshowImage
are variables that you will need to define in your component. Also, adjust the class names to match the desired styling.