Manihtraa
Manihtraa

Reputation: 988

How to set Angular 4 background image?

I am trying the following lines to set the background image.but it not works. what are the way set background image in constantly in my application.

app.component.html

<div [ngStyle]="{'background' : 'url(./images/trls.jpg)'}">
    <router-outlet></router-outlet>
    <alert></alert>
</div>

Upvotes: 58

Views: 216703

Answers (9)

Abel Chipepe
Abel Chipepe

Reputation: 462

This can be done with a custom directive, instead of having a method that will execute in a loop affecting performance.

In my case I would created a BackImgDirective like this:

import {Directive, ElementRef, Input, OnInit, Renderer2} from "@angular/core";
@Directive({ selector: '[appBackImg]'})
export class BackImgDirective implements OnInit {
    @Input() appBackImg = ''
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    ngOnInit() {
     this.setBackImg()
    }

    setBackImg(){
     this.renderer.setStyle(this.el.nativeElement, 'background-image', 'url(' + this.appBackImg + ')')
    }
}

And use it like this:

<div [appBackImg]="slide.image"> </div>

Upvotes: 2

user2668735
user2668735

Reputation: 1205

A very easy solution is to declare the image with a loading class and remove this class when image is loaded. You can then customize the placeholder in CSS, as it should be.

HTML :

        <img class="persona-avatar loading" #avatar
             (load)="avatar.classList.remove('loading'); "
             src="/assets/img.png"
             alt=""/>

SCSS :

        .persona-avatar {
          width: 50px;
          height: 50px;
          &.loading {
            background-image: url("data:image/png;base64,iVBORw0K...");
            background-size: contain;
          }
        }

It is better to use a base64 image to not have the same load problem with the placeholder.

Upvotes: 1

Akash Agrawal
Akash Agrawal

Reputation: 2299

You can use ngStyle to set background for a div

<div [ngStyle]="{background-image: 'url(./images/' + trls.img + ')'}"></div>

or you can also use built in background style:

<div [style.background-image]="'url(/images/' + trls.img + ')'"></div>

Upvotes: 91

Murry is Developing
Murry is Developing

Reputation: 296

If you plan using background images a lot throughout your project you may find it useful to create a really simple custom pipe that will create the url for you.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'asUrl'
})
export class BackgroundUrlPipe implements PipeTransform {

  transform(value: string): string {
    return `url(./images/${value})`
  }

}

Then you can add background images without all the string concatenation.

<div [ngStyle]="{ background: trls.img | asUrl }"></div>

Upvotes: 6

Rahul Uttarkar
Rahul Uttarkar

Reputation: 3645

In Html

<div [style.background]="background"></div>

In Typescript

this.background= 
this.sanitization.bypassSecurityTrustStyle(`url(${this.section.backgroundSrc}) no-repeat`);

A working solution.

What is the recommended way to dynamically set background image in Angular 4

Upvotes: 2

Nodira
Nodira

Reputation: 666

I wanted a profile picture of size 96x96 with data from api. The following solution worked for me in project Angular 7.

.ts:

  @Input() profile;

.html:

 <span class="avatar" [ngStyle]="{'background-image': 'url('+ profile?.public_picture +')'}"></span>

.scss:

 .avatar {
      border-radius: 100%;
      background-size: cover;
      background-position: center center;
      background-repeat: no-repeat;
      width: 96px;
      height: 96px;
    }

Please note that if you write background instead of 'background-image' in [ngStyle], the styles you write (even in style of element) for other background properties like background-position/size, etc. won't work. Because you will already fix it's properties with background: 'url(+ property +) (no providers for size, position, etc. !)'. The [ngStyle] priority is higher than style of element. In background here, only url() property will work. Be sure to use 'background-image' instead of 'background'in case you want to write more properties to background image.

Upvotes: 1

netalex
netalex

Reputation: 457

this one is working for me also for internet explorer:

<div class="col imagebox" [ngStyle]="bkUrl"></div>

...

@Input() background = '571x450img';  
bkUrl = {};   
ngOnInit() {
    this.bkUrl = this.getBkUrl();
  }
getBkUrl() {
    const styles = {
      'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
    };
    console.log(styles);
    return styles;
  }

Upvotes: 1

Sachin Hatikankan
Sachin Hatikankan

Reputation: 459

Below answer worked for angular 4/5.

In app.component.css

.image{
     height:40em; background-size:cover; width:auto;
     background-image:url('copied image address');
     background-position:50% 50%;
   }

Also in app.component.html simply add as below

<div class="image">
Your content
</div>

This way I was able to set background image in Angular 4/5.

Upvotes: 8

Richard Strickland
Richard Strickland

Reputation: 1841

This works for me:

put this in your markup:

<div class="panel panel-default" [ngStyle]="{'background-image': getUrl()}">

then in component:

getUrl()
{
  return "url('http://estringsoftware.com/wp-content/uploads/2017/07/estring-header-lowsat.jpg')";
}

Upvotes: 31

Related Questions