html - Obtener el valor en píxeles de un estilo CSS a través de Angular
Estoy intentando obtener el valor exacto en píxeles de un estilo margin-left aplicado a un elemento div con la función calc(), necesito que este valor se envíe a una función en mi TypeScript, hasta ahora mi código para esto se ve de la siguiente manera
HTML :
<div id="cont" class="container" [style.width.px]="getWidth()"
[ngStyle]="getOffset([style.margin-left])">
TypeScript :
getOffset(marg){
var style;
if(marg > 130){
style = {'margin-left': 'calc(50% -'+String(this.offsets[this.arrPosWidth])+'px)' };
}else{
style = {'margin-left': '130px' };
}
return style
}
Enviar el estilo a través de esa función era una apuesta arriesgada y he intentado acceder al estilo margin-left con element.style, pero esto solo devuelve una cadena literal con calc(50%-..px). ¿Hay alguna manera de obtener el valor en píxeles del estilo margin-left aplicado a ese elemento en particular?
Respuesta #1
Puedes lograr esto a través del hook del ciclo de vida ngAfterContentInit.
Aquí hay un ejemplo funcional: https://stackblitz.com/edit/angular-dbfp8x
export class AppComponent implements AfterViewInit {
// this is what we initially set the margin to
public margin:number = 75;
// Bound to your element
@ViewChild('myElem') element: ElementRef;
ngAfterViewInit(){
// get the current margin and then strip off the 'px'
let currentMargin:number = parseInt((this.element.nativeElement.style.marginLeft as string).substring(0,2));
// add any restriction logic you need.
if(currentMargin > 25){
this.margin = 25;
}
}
}