Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda