2017-08-11 96 views
1

如何通過ngOnInit將圖片添加到背景中? 我不想在CSS中使用background: url("link of my image"),因爲這會增加我網站的負載。我想通過角2打字稿做到這一點Angular 2中的背景圖片

+0

據我所知在css中完成的樣式更快,然後在js中完成。 – onetwo12

+0

真的嗎? 我的着陸載入所有內容,之後我看到圖像和登錄表單。我需要加載登錄表單,並在同一時間加載圖像 –

回答

1

你覺得沒錯!它可以通過很多方式完成!

1)通過改變風格輸入:

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)通過改變ngClass:

而且在ngOnInit()設置要

3的可變)加入指令:

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

還有很多ot她在這個來源的方式,例如: https://juristr.com/blog/2016/01/learning-ng2-dynamic-styles/

1

在你component.ts,進口DomSanitizer

進口{} DomSanitizer從「@角/平臺的瀏覽器;

... delare在你的組件類的變量,說backgroundImageStyle和初始化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); 
} 

,並在組件的HTML,設置您的主要容器的樣式屬性:

[style]="backgroundImageStyle" 
+0

它不工作... –

+0

對不起,我犯了一個錯誤,看到更新的答案 – Faisal

+0

謝謝!現在它可以工作 –