3

I am trying to append an inline CSS rule for background-image using a dynamic variable set inside the constructor like so:

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

then in my Component:

export class SomeComponent {

  backgroundImage = '';

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

}

However, when the element is rendered to the screen, the inline CSS rule gets omitted.

I tried using Angular's ng-style, but it returns "Can't bind to 'ng-style' since it isn't a known property of 'div'".

I also tried setting styles inside my @Component declaration as noted in this answer, but this wouldn't fly in my case, as I need the backgroundImage variable to be dynamic.

1 Answer 1

6

Since Ionic2 (or just Ionic) is built on top of Angular (an not AngularJS), you can do that like this:

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

or

<div [style.background]="'url(' + backgroundImage + ')'"></div>
Sign up to request clarification or add additional context in comments.

2 Comments

2nd one worked for me on Ionic 3 as [style.borderColor]="stat.color" with no interpolation. Thanks
Glad to hear that @Ruffo :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.