Q:

angular 2 img width sets to 0

So I am setting the image source and width dynamically in my template.  The problem I see is that it sets the width to 0.  
The template looks like:
<img src="{{item.msg}}" width="{{item.width}}" style="float:right" *ngIf="item.templateType == 'image'" />{{item.width}}

The value is passed as below from .ts
this.items.push(new ImageMessage('http://someimage.png', '100%'));

What I see is that it does not display the image but prints the value of item.width correctly.  Looking into inspector it shows the width is set to 0 which explains why image is not appearing.  
However, I am failing to understand why the width is getting set to 0 in img tag. 
Please help. 
Thanks. 

A:

You can set the width as a percentage using one-way binding syntax [style.width.%] targeting the style attribute binding of an element like <img /> in your example.  HTML5 does require that the width property is in pixels, so using the [style.width.%] attribute binding would allow you to set the width as a percentage. 
You're ImageMssage object would need to have the percentage '%' character removed from the width value of the ImageMessage object to make this work.  With this syntax, it's flexible to work with either strings or numbers.  Either '100' or 100 would work. 
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {CommonModule} from '@angular/common';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>

      <div *ngFor="let item of items">
        <img [src]="item.msg" [style.width.%]="item.width" style="float:right;" />
      </div>
    </div>
  `,
})
export class App {
  name:string;
  items: any[];

  constructor() {
    this.items = [
      { msg: 'http://placehold.it/800', width: '100' },
      { msg: 'http://placehold.it/800', width: '75' },
      { msg: 'http://placehold.it/800', width: 50 },
      { msg: 'http://placehold.it/800', width: '25' }
    ];
  }
}

@NgModule({
  imports: [ BrowserModule, CommonModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

If you want to set the pixels, you can use the following:
<img [src]="item.msg" [style.width.px]="item.width" ... />{{item.width}}px

Here is a plunker demonstrating the functionality. 
Hopefully this helps!