如何从css Angularjs2访问组件变量

时间:2017-03-08 03:07:52

标签: css angular angularjs-directive

home.component.css

#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'
}

2 个答案:

答案 0 :(得分:0)

只需调用变量,但需要使用angular属性。

在角度1中,我相信我们可以在值内使用ng-src或src宽度currly括号。在角度2中,我们可以这样做:

<img [src]="parallax_image_path">

答案 1 :(得分:0)

你无法从home.component.css访问它,如果你正在尝试做什么,但你可以使用[ngStyle] angular指令达到相同的效果。

&#13;
&#13;
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 + ')');
  }

}
&#13;
<div [style.background-image]="backgroundImg"></div>
&#13;
&#13;
&#13;