![](/img/trans.png)
[英]How can I read an CSS variable in :root from an Angular component?
[英]how can i access component variable from css Angularjs2
主頁.component.css
#first-example {
margin-top: 20%;
/*parallax_image_path not working*/
background-image: url({{parallax_image_path}});
}
主頁.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'
}
只需調用變量,但您需要 angular 屬性。
在 Angular 1 中,我相信我們可以在值內使用 ng-src 或 src 寬度大括號。 在 angular 2 中,我們可以這樣做:
<img [src]="parallax_image_path">
如果這是你想要做的,你不能從 home.component.css 訪問它,但你可以使用 [ngStyle] angular 指令實現相同的效果。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.