2017-06-17 40 views
2

我试图使用动态变量设置constructor内像这样追加内联CSS规则background-image样式组件 - Ionic2,AngularJS

<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变量是动态的。

回答

4

由于Ionic2(或只是离子)是建立在(一股不AngularJS)上面,你可以做这样的:

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

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

完美!谢谢! –

+1

第二个人在Ionic 3上为我工作[style.borderColor] =“stat.color”,没有内插。谢谢 – Ruffo

+1

很高兴听到@Ruffo :) – sebaferreras