2017-08-11 2 views
1

Wie füge ich Hintergrundbilder von ngOnInit hinzu? Ich möchte nicht background: url("link of my image") in CSS verwenden, da dies die Auslastung meiner Website erhöht. Ich möchte dieseHintergrundbild in Angular 2

+0

Soweit ich weiß Styling in css getan ist schneller als in js getan. – onetwo12

+0

Wirklich? Meine Landung laden alle und danach sehe ich Bild und Login-Formular. Ich muss Login-Formular laden und gleichzeitig das Bild laden –

Antwort

1

Sie denken richtig! Es kann auf viele Arten gemacht werden!

1) Durch Änderung der Stil-Eingang:

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) Durch die Änderung ngClass:

Und in ngOnInit() stellen Sie Ihre Variable, die Sie

3 wollen) Durch das Hinzufügen Direktive:

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'); 
    } 
} 

Und viele ot Ihre Wege in dieser Quelle zum Beispiel: https://juristr.com/blog/2016/01/learning-ng2-dynamic-styles/

1

In Ihrem component.ts von Angular 2 Typoskript tun, Import DomSanitizer,

Import {DomSanitizer} von '@ Winkel/Plattform-Browser';

... eine Variable in der Komponentenklasse delare, sagen backgroundImageStyle und initialisieren diese 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); 
} 

und in der Komponente HTML, stellen Sie den Stil-Eigenschaft des Hauptbehälters:

[style]="backgroundImageStyle" 
+0

Es funktioniert nicht ... –

+0

Entschuldigung, ich habe einen Fehler gemacht, sehen Sie die aktualisierte Antwort – Faisal

+0

Vielen Dank! Jetzt funktioniert es –