Home > Mobile >  Dynamically build div on button click when button is also created dynamically
Dynamically build div on button click when button is also created dynamically

Time:08-06

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: '[email protected]'
        },            {
            id: 2,
            name: "someOneElseName",
            faseOne: true,
            faseTwo: false,
            contact: "Someone Elses name",
            email: '[email protected]'
        },

    getCollectables() {
        return this.collectables;
    }
]

My component.html:

<div >
  <div  *ngFor="let item of collectables | pipeOne">
    <button >{{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

CodePudding user response:

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 >
  <div  *ngFor="let item of collectables | pipeOne">
    <button  (click)='selectedItem=item'>{{item.name}}</button>
  </div>
</div>
<div *ngIf='selectedItem'>
    <h1>{{selectedItem.name}}</h1>
    <h2>{{selectedItem.contact}}</h2>
</div>
  • Related