Reputation: 46976
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
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
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