Home > database >  How can I use data from JSON file to set the width of some HTML elements?
How can I use data from JSON file to set the width of some HTML elements?

Time:03-07

I want to get specific data from JSON objects and use it to set the width of various tags.

The JSON object is like this:

"habilidades": [
    {
        "name": "Manejo del Tiempo",
        "description": "Capacidad para priorizar tareas a fin de cumplir con los plazos.",
        "percentage": "85%",
        "width": "85%"
    },
    {
        "name": "Trabajo en Equipo",
        "description": "Facilidad para trabajar en grupos interdisciplinarios",
        "percentage": "90%",
        "width": "90%"
    },
   ]

I have a service that sends a GET request that returns the set of data:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
 providedIn: 'root'
})
export class PortfolioService {

 constructor(private http: HttpClient) { }

 obtenerDatos(): Observable<any> {
  return this.http.get('./assets/data/data.json');
 }
}

Then, the component suscribes to this and assigns the array to a variable:

export class HabilidadesComponent implements OnInit {
  
  habilidadesList: any;
  constructor(private datosPortfolio: PortfolioService) { }
  
  ngOnInit(): void {
    this.datosPortfolio.obtenerDatos().subscribe(data => {
      this.habilidadesList = data.habilidades;
    })
  }
}

So far so good (I think)... Then, in HTML I have a *ngFor directive that iterates through the array:

<div *ngFor="let habilidad of habilidadesList">
 <div >
  <div>
   <h4 >{{ habilidad.name }}</h4>
   <p>{{ habilidad.description }}</p>
   <div >
   <span style="width: ">{{ habilidad.percentage }}</span> <!-- I want habilidad.width value to set the width of span.-->
  </div>
 </div>
</div>

I want habilidad.width to set the width of the <span> element. I can't realize how to do this. I've tried property binding, using the *ngStyle directive but couldn't make it work.

CodePudding user response:

You can bind the width using [style.width.%]

<span [style.width.%]="habilidad.width"></span> 

You can also make use of px, em like below

<div [style.width.em]="width"> Width Size with em</div>
<div [style.width.pt]="width"> Width Size with pt</div>
  • Related