javascript - Interpolera en variabel som en inline-stilparameter i komponentens mall?
Detta är komponentmallen:
<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>
Och komponentklassen:
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() {
}
}
Jag trodde att det skulle vara möjligt att lägga till crop-inmatningsvärdet i mallen på detta sätt:
margin: {{crop}} 0 {{crop}} 0;"
Men detta fungerar inte. Tankar?
Svar #1
För att interpolera stilattribut behöver du använda NgStyle-direktivet på följande sätt:
<img [ngStyle]="{'margin': margin}"/>
och i komponent
get margin() {
return `${this.crop} 0 ${this.crop} 0`
}
Du kan ta en titt på den officiella dokumentationen här: https://angular.io/api/common/NgStyle
Svar #2
NgStyle skulle vara det perfekta alternativet, men om du behöver hålla fast vid din exekveringsmodell kan du försöka använda CSS-variabler för att ställa in marginalen.
Hitta Stackblitz-demo där färgen ändras på ett liknande sätt.
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>
