简体   繁体   中英

Angular ngStyle inside img tag not updating dynamically

With this template

  <img  src="{{someDynamicImageSrcVar}}" 
  (load)="onImageLoad($event)"
  [ngStyle]="getImageStyle()"                
  >

After the image is changed and loads, onImageLoad() updates some properties.

getImageStyle() {
  const style = {
    'width.px': this.naturalWidth,
    'height.px': this.naturalHeight
  };
  console.log(style);
  return style;
}

The framework calls getImageStyle() which returns a style like

{width: "500px", height: "400px"}

However, the DOM is not updated apart from the first time getImageStyle() was called.

The style never changes from the initial values.

What should I do to make the style update?

ngStyle is work like this

[ngStyle]="{'color': 'blue', 'font-size': '24px', 'font-weight': 'bold'}"

The syntax for ngStyle is this

[ngStyle]="{'width.px':500, 'height.px': 500}"

So change your return object to this structure

{ 'width.px' : 500, 'height.px' : 500}

the code is looks good! if you really returned {width: "500px", height: "400px"} i think you should return the value with single qutation like {width: '500px', height: '400px'}

I hope to help more :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM