4

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?

Ole
  • 41,793
  • 59
  • 191
  • 359
  • 2
    I would suggest looking into [ngStyle](https://angular.io/api/common/NgStyle). [This](https://stackoverflow.com/questions/49280975/angular-how-to-apply-ngstyle-conditions) might help. – Shazvi Oct 05 '19 at 07:49

2 Answers2

2

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

Tiago Viegas
  • 181
  • 6
1

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>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
  • 1
    That CSS property explanation is sweet! Thanks for pointing that out! Will be playing with that for sure. – Ole Oct 05 '19 at 11:58