Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!