Thursday 5 September 2019

Image stretches to 100% while loading when server-side rendering

I have the following code which uses Angular Material to make my image responsive:

<picture [ngStyle.xs]="{'width': '100%'}" [ngStyle.gt-xs]="{'width': '448px', 'height': '60px'}">
  <source srcset="/assets/images/logo-text-lg.webp" type="image/webp" [ngStyle.xs]="{'width': '100%'}" [ngStyle.gt-xs]="{'width': '448px', 'height': '60px'}">
  <source srcset="/assets/images/logo-text-lg.png" type="image/png" [ngStyle.xs]="{'width': '100%'}" [ngStyle.gt-xs]="{'width': '448px', 'height': '60px'}">
  <img src="/assets/images/logo-text-lg.png" alt="TechScore" [ngStyle.xs]="{'width': '100%'}" [ngStyle.gt-xs]="{'width': '448px', 'height': '60px'}">
</picture>

The goal is to have it exactly 448x60 unless it is on an extra small screen. Then it should be 100% of the page width. This works except that, since I implemented server-side rendering via Angular Universal, I get a flash of the image at 100% even on larger screens.

stretched image

image once loaded

If I look at the source (with caching disabled) I can see that the markup coming from the server includes style="width: 100%" which means that the server-side rendered version thinks that the screen is extra small.

How can I let Angular Universal known what the screen resolution is and how do I pass that information on to Angular Material and override what it thinks is the resolution so that it chooses the correct width?

Update

I thought I was onto something by detecting if it was a mobile browser via the user-agent string and then setting the default breakpoints as described here: https://github.com/angular/flex-layout/wiki/Using-SSR-with-Flex-Layout

FlexLayoutModule.withConfig({ssrObserveBreakpoints: [isMobile() ? 'xs' : 'md']})

but I must be doing it wrong because I'm not seeing any effect.



from Image stretches to 100% while loading when server-side rendering

No comments:

Post a Comment