Ole
Ole

Reputation: 46976

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?

Upvotes: 4

Views: 2155

Answers (2)

Nidhin Joseph
Nidhin Joseph

Reputation: 10237

NgStyle would be the perfect option, but if you need to stick with your model of execution, you may try using CSS variables to set the margin.

Find the Stackblitz demo where the colour is changed in a similar manner.

hello.component.ts

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

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { 
    font-family: Lato;
    color: var(--hello-color); 
  }`]
})
export class HelloComponent implements OnInit {
  @Input() color: string; 

  constructor(public element: ElementRef) {

  }

  ngOnInit() {
    this.element.nativeElement.querySelector('h1').style.setProperty('--hello-color', this.color);​
  }
}

style.css

/* Add application styles & imports to this file! */
:root{
  --hello-color: red;
}

app.component.html

<hello color="{{ color }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

Upvotes: 1

Tiago Viegas
Tiago Viegas

Reputation: 201

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

Upvotes: 2

Related Questions