Dynamically build div on button click when button is also created dynamically

Viewed 42

Working hard on my angular skills. stackoverflow has been really helpfull on getting my first own app together.

My app uses a service:: collectable.service.ts:

export class CollectableService {
    private collectables: Collectable[] = [
        {
            id: 1,
            name: "someName",
            faseOne: false,
            faseTwo: true,
            contact: "Someones name",
            email: 'email1@test.com'
        },            {
            id: 2,
            name: "someOneElseName",
            faseOne: true,
            faseTwo: false,
            contact: "Someone Elses name",
            email: 'email2@test.com'
        },

    getCollectables() {
        return this.collectables;
    }
]

My component.html:

<div class="col">
  <div class="btn-group m-3" *ngFor="let item of collectables | pipeOne">
    <button class="btn btn-success">{{item.name}}</button>
  </div>
</div>
<div id="dynamicDiv"></div> // here I want to show the rest of the values out of the array

Example pipeOne (I have one pipe per fase):

  transform(pipeOne: any[], ...args: unknown[]): any[] {
    return pipeOne.filter(p => p.faseOne == true);
  }

Now when the button is clicked, I want to display the other values of the object in the array into div #dynamicDiv. In this example because of faseOne equals true, I need access to the values of the first object in the array, with ID 1. So I can display only the values of object id 1

<div id="dynamicDiv>
    <h1>{{item.name}}</h1>
    <h2>{{item.contact}}</h2>
</div>

etc...

Hope you guys understand and can help me get further

1 Answers

You can add one more property to your component as selectedItem, and assign it on button click, for example;

@Component(...)
export class MyComponent {
  selectedItem: Collectable;
}

And in your MyComponent template

<div class="col">
  <div class="btn-group m-3" *ngFor="let item of collectables | pipeOne">
    <button class="btn btn-success" (click)='selectedItem=item'>{{item.name}}</button>
  </div>
</div>
<div *ngIf='selectedItem'>
    <h1>{{selectedItem.name}}</h1>
    <h2>{{selectedItem.contact}}</h2>
</div>
Related