2017-03-08 10 views
1

home.component.css如何從CSS Angularjs2訪問組件變量

#first-example { 
    margin-top: 20%; 
    /*parallax_image_path not working*/ 
    background-image: url({{parallax_image_path}}); 
} 

home.component.html

<div class="main_container"> 

    <div class="main_content"> 
    <h2>Coming Soon</h2> 
    </div> 

    <div parallax id="first-example"></div> 

</div> 

home.component.ts

import {Component} from "@angular/core"; 
/** 
* Created by sai on 3/7/17. 
*/ 
@Component({ 
    selector: "home", 
    templateUrl: './home.component.html', 
    styleUrls: ['./home.component.css'] 
}) 
export class Home { 
    parallax_image_path = '/assets/website_background.jpg' 
} 
+0

的可能的複製[如何使用ngStyle(angular2)添加背景圖片?](http://stackoverflow.com/questions/34875426/how-to-add-background- image-using-ngstyle-angular2) – JayChase

回答

0

只需調用該變量,但你需要角度屬性。

在angular 1中,我相信我們可以在值內使用ng-src或src寬度大括號。在角2,我們可以這樣來做:

<img [src]="parallax_image_path">

+0

我如何在.css文件中做到這一點? –

+0

@SaiKiran在你的組件中。你有'styleUrls數組'。將它存儲在那裏。 –

0

不能從home.component.css訪問它,如果這就是你企圖做的,但你可以使用達到同樣的效果[ngStyle ]角度指示。

import { Component, OnInit, Input } from '@angular/core'; 
 
import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; 
 

 
@Component({ 
 
    selector: 'my-component', 
 
    templateUrl: './my-component.component.html', 
 
    styleUrls: ['./my-component.component.scss'] 
 
}) 
 

 
export class MyComponent implements OnInit { 
 

 
    private backgroundImg: SafeStyle; 
 
    @Input() myObject: any; 
 

 
    constructor(private sanitizer: DomSanitizer) {} 
 

 
    ngOnInit() { 
 
    this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')'); 
 
    } 
 

 
}
<div [style.background-image]="backgroundImg"></div>