【问题标题】:how can i access component variable from css Angularjs2我如何从 css Angularjs2 访问组件变量
【发布时间】:2017-07-28 11:37:07
【问题描述】:

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

【问题讨论】:

标签: css angular angularjs-directive


【解决方案1】:

只需调用变量,但您需要角度属性。

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

<img [src]="parallax_image_path">

【讨论】:

  • 如何在 .css 文件中执行此操作?
  • @SaiKiran 在你的组件中。你有styleUrls array。把它存放在那里。
【解决方案2】:

如果你想这样做,你不能从 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 + ')');
  }

}
&lt;div [style.background-image]="backgroundImg"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 2021-10-31
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 2017-06-03
    相关资源
    最近更新 更多