使用内联CSS设置组件样式 - Ionic2,AngularJS

时间:2017-06-17 05:29:01

标签: css angular typescript ionic2 ionic3

我正在尝试使用background-image内的动态变量集为constructor添加内联CSS规则,如下所示:

<div style="background-image: url('{{backgroundImage}}');">
  ...
</div>

然后在我的组件中:

export class SomeComponent {

  backgroundImage = '';

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.backgroundImage = 'https://unsplash.it/200/300' ; }

}

但是,当元素呈现到屏幕时,内联的 CSS规则将被忽略。

我尝试使用Angular的ng-style,但它返回“无法绑定到'ng-style',因为它不是'div'的已知属性”。

我还尝试在styles声明中设置@Component,如this answer中所述,但这不会出现在我的情况下,因为我需要backgroundImage变量来充满活力。

1 个答案:

答案 0 :(得分:5)

由于Ionic2(或Ionic)建立在 Angular (非AngularJS)之上,你可以这样做:

<div [ngStyle]="{ background: 'url(' + backgroundImage + ')' }"></div>

<div [style.background]="'url(' + backgroundImage + ')'"></div>