2017-07-26 660 views
0

我有一個Angular 2應用程序。在這個應用程序中,我有幾個組件。我想僅爲登錄組件添加背景圖片。我怎麼做?如何在Angular 2組件中添加背景圖片?

body{ 
    background-image: url('https://s.zkcdn.net/Advertisers/d36ea4926dfa4978ab2556ba7688692c.png') ; 
    background-position: center; 
    background-repeat: no-repeat; 
    background-size: cover; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    height:100%; 

} 

我有這種樣式的登錄組件。但它不覆蓋整個窗口。它只覆蓋表單部分。

+3

[所以] *不是*自由代碼編寫的服務。預計你會嘗試**自己編寫代碼**。在[做更多研究]之後(http://meta.stackoverflow.com/questions/261592),如果你有問題,你可以**發佈你已經嘗試過**的清單,說明什麼是不工作的**並提供** [mcve] **。我建議閱讀[問]一個好問題和[完美問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。另外,一定要參加[旅遊]。 – Igor

回答

0

@Component您的登錄組件的裝飾器中,您可以添加一個styleUrls字段。這樣做只允許您爲登錄組件使用樣式表。

@Component({ 
    selector: 'your-selector' 
    templateUrl: ['path/to/your/html/component'], 
    styleUrls: ['path/to/your/stylesheet'], 
}) 

然後,您可以在您的樣式表,改變你的背景只爲login組件

+0

body { background-image:url('https://s.zkcdn.net/Advertisers/d36ea4926dfa4978ab2556ba7688692c.png'); background-position:center; background-repeat:no-repeat; background-size:cover; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; 身高:100%; } – RohanG

+1

我有這種風格的登錄組件。但它不覆蓋整個窗口。它只覆蓋表單部分。 – RohanG

+0

你可以嘗試添加一個'div'封裝你的身體並設置這個div的背景。不知道爲什麼你有這個結果,檢查你的組件是如何在另一個 – Octoverflow

0

你能分享你的代碼?

我正在使用Ionic 3.但Ionic使用Angular。

在我的login.html頁我有這樣的:

<ion-content class="background"> 
... 
</ion-content> 

我認爲你可以試試:

<body class="background"> 
</body> 

在我login.scss頁我有這樣的:

page-login { 
    .background { 
     // Path of my picture 
     background-image: url('../assets/background.gif'); 
    } 
} 

此致敬禮,

1

我面臨同樣的問題。但下面的代碼適合我。

在全局css文件(style.css)中添加以下css代碼。

.bg-img 
{ 
    background-image: url('/assets/images/back.jpg'); 
    background-position: center; 
    background-repeat: no-repeat; 
} 

,並添加在需要component.ts文件ngOnInit部下面的代碼(例如:login.component.ts)

ngOnInit() { 
    document.body.classList.add('bg-img'); 
} 
+0

這可以工作,但不知何故,每當我改變組件,背景卡住,直到我刷新頁面。有沒有解決這個問題的方法? –