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
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
- As far as I know styling done in css is faster then done in js. – onetwo12 Commented Aug 11, 2017 at 8:57
- Really? My landing load all and after that i see image and login form. I need to load login form and at the same time load the image – Sergey Andreev Commented Aug 11, 2017 at 9:01
2 Answers
Reset to default 3In your ponent.ts, import DomSanitizer
,
import { DomSanitizer } from '@angular/platform-browser';
... delare a variable in your ponent 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 ponent html, set the style property of your main container:
[style]="backgroundImageStyle"
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./blog/2016/01/learning-ng2-dynamic-styles/