Search code examples
angularbackground-image

How to keep several different photos files and choose one as background based on screen size?


Starting from something like this in my .html file:

<mat-sidenav-content
    [ngStyle]="{'background-image': 'url(' + backgroundImageURL + ')',
        'background-size': backgroundSize, 'background-repeat': backgroundRepeat,
         'background-position': 'center center'}">
</mat-sidenav-content>

where backgroundImageURL, backgroundSize and backgroundRepeat are variables which I define in the something like "environment.ts" file,

how could I keep 3 different image files (eg _-small, _-medium, _-large), and apply one of them or the other depending on the screen size ?

Thanks.


Solution

  • you can easily do that with for example a getter :

    get backgroundImgUrl() {
       if (window.innerWidth > 1000) {
           return 'http://path-to-image.jpg';
       } else ...
    }
    

    But you should rather use srcset property : https://developer.mozilla.org/fr/docs/Apprendre/HTML/Comment/Ajouter_des_images_adaptatives_%C3%A0_une_page_web wich is html built-in.