0

Using Angular 2, what is the difference between using the following 2 options for passing a variable value to a style? Are there pros and cons, or is it just personal choice, or is one more flexible/meant for other uses.

Option 1

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

Option 2

<div [style.background-image]="'url(' + image + ')'">

Related:

Attribute property binding for background-image url in Angular 2

How to add background-image using ngStyle (angular2)?

Community
  • 1
  • 1
redfox05
  • 3,354
  • 1
  • 34
  • 39

1 Answers1

0

Option 1

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

The styles are updated according to the value of the expression and set within the component. You would want to use this when adding multiple inline styles at once. For example, you may want to do something like:

// Component

stylize() {
  let style = {
    'font-style': 'italic',
    'font-weight': 'bold'
  };
  return style;
}



// Template

<div [ngStyle]="stylize()">
  This font is italic and bold.
</div>

Option 2

<div [style.background-image]="'url(' + image + ')'">

This allows for inline styling as you have. However, this will only work for that div itself.

Tucker
  • 1,722
  • 2
  • 10
  • 12