Background image in Angular 2

How to add picture to background by ngOnInit? I do not want to use background: url("link of my image") in CSS because this increases the load of my site. I want to do this by Angular 2 Typescript

Answers:

Answer

You think right! It can be done by many ways!

1) By change the style input:

import {Component} from '@angular/core'
import { DomSanitizer  } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div [style]="getStyle()">
        I am a div that wants to be styled
      </div>
      <button (click)="showStyle = !showStyle;">Toggle style</button>
    </div>
  `
})
export class App {
  showStyle: false;

  constructor() {
  }

  getStyle() {
    // snip snip -> fetch the url from somewhere
    const profilePicUrl = 'some-remote-server-url.jpg';
    const style = `background-image: url(${profilePicUrl})`;
    // sanitize the style expression
    return this.sanitizer.bypassSecurityTrustStyle(style);
  }
}

2) By change ngClass:

And in ngOnInit() set your variable that you want

3) By adding directive:

import {Directive, ElementRef, Renderer} from '@angular/core';

@Directive({
  selector: '[setBackgroundImage]',
})
export class StyledDirective {
  constructor(public el: ElementRef, public renderer: Renderer) {
    // el.nativeElement.style.backgroundColor = 'yellow';
    renderer.setElementStyle(el.nativeElement, 'backgroundImage', 'yourImageLink');
  }
}

And many other ways in this source for example: https://juristr.com/blog/2016/01/learning-ng2-dynamic-styles/

Answer

In your component.ts, import DomSanitizer,

import { DomSanitizer } from '@angular/platform-browser';

... delare a variable in your component class, say backgroundImageStyle and initialize this variable in ngOnInit:

backgroundImageStyle: string; 

constructor(private sanitizer: DomSanitizer) { }

public ngOnInit()
{
    this.backgroundImageStyle = this.getBackgroundImageStyle();
}

private getBackgroundImageStyle()
{
    let backgroundImage = './path/to/your/image';

    // sanitize the style expression
    const style = `background-image: url(${backgroundImage})`;
    return this.sanitizer.bypassSecurityTrustStyle(style);
}

and in your component html, set the style property of your main container:

[style]="backgroundImageStyle"

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.