Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating a variable as an inline style parameter of the component template?

This is the component template:

<div style="max-width: 100rem;
            margin-top: 5rem;
            min-height: 20rem; 
            overflow: hidden;">
    <img style="width: 100%; 
                height: auto;  
                margin: -20% 0 -20% 0;" 
        [src]="src">
</div>

And the component class:

    import { Input, Component, OnInit } from '@angular/core';

    @Component({
      selector: 'image',
      templateUrl: './image.component.html',
      styleUrls: ['./image.component.scss']
    })
    export class ImageComponent implements OnInit {
      @Input() src;
      @Input() crop = "-20%"

      constructor() { }

      ngOnInit() {
      }
    }

I thought it would be possible to add the crop input value into the template like this:

    margin: {{crop}} 0 {{crop}} 0;" 

However this does not work. Thoughts?

like image 404
Ole Avatar asked Sep 05 '25 10:09

Ole


1 Answers

In order to interpolate style properties you need to use NgStyle directive like so:

<img [ngStyle]="{'margin': margin}"/>

and in component

get margin() { 
  return `${this.crop} 0 ${this.crop} 0`
}

You can take a look on official docs here: https://angular.io/api/common/NgStyle

like image 139
Tiago Viegas Avatar answered Sep 08 '25 19:09

Tiago Viegas