Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
How to dynamically use model variables in ngFor loop using AngularJS 2/4?

I have the following object in my component that my template uses to render divs:

this.myobj = {'machine':['parts':[
                            {'gears': [{'name': 'AName1'}, {'name': 'AName2'}]},
                            {'screws': [{'name': 'BName2'}, {'name': 'BName3'}]},
                            {'rotors': [{'name': 'CName5'}]},
                            {'shells': [{'name': 'CName2'}]}
             ]]}

My current code is:

<button (click)="setPart('gears')">Gears</button>
<button (click)="setPart('screws')">Screws</button>
<button (click)="setPart('rotors')">Rotors</button>
<button (click)="setPart('shells')">Shells</button>

<div *ngFor="let part of machine[0]?.parts[1].gears;let i = index;" style="color:#FFF">
<div> {{part.name}}</div>
</div>

My issue is I want to make it so that I can dynamically "change" the ngFor to iterate over different parts and create divs for the names under them (i.e. 'rotors', 'shells') by clicking on one of the four buttons above it. Currently the way I have it, it is hardcoded only to a single part ('gears').

I really don't like the hardcoding of parts[1].gears as I ideally want to set "1" and "gears" using variables on scope. Or is this not possible to have variables like this in ngFor?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Create a property in your component:

myPart: any;

Change your template to:

<div *ngFor="let part of mypart;let i = index;" style="color:#FFF">
    <div>{{part.name}}</div>             
</div>

Change your method:

setPart(name: string){
    this.myPart = this.myobj.machine[0].parts[name];
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda