0

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?

1 Answer 1

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.