Shyam Nair
Shyam Nair

Reputation: 159

How to create a dynamic button using dynamic data and get dynamic values on the button click in angular

Here i am getting below Dynamic data from server

{
    "data": [
        {
            "id": 4,
            "first_name": "Eve",
            "last_name": "Holt",
            "lat":"25.6599899",
            "lng":"45.3664646",
            "status":"0"

        },
        {
            "id": 5,
            "first_name": "Charles",
            "last_name": "Morris",
            "lat":"25.99899",
            "lng":"45.4646",
             "status":"1"

        },
        {
            "id": 6,
            "first_name": "Tracey",
            "last_name": "Ramos",
            "lat":"25.2339899",
            "lng":"45.56664646",
            "status":"1"

        }
    ]
}

Here how to create the Dynamic buttons based on the Status value suppose if status=1 value having 3 members then 3 buttons have to be created with that particular names and ids and when the user clicks any button that particular of the person and name has to be displayed on alert

Upvotes: 0

Views: 151

Answers (1)

Dhaval kansagara
Dhaval kansagara

Reputation: 561

As is understand like you need button for each status = 1 and on click need to display name of person.

ts code

Variable

public dynamicData = {
"data": [
  {
    "id": 4,
    "first_name": "Eve",
    "last_name": "Holt",
    "lat": "25.6599899",
    "lng": "45.3664646",
    "status": "0"

  },
  {
    "id": 5,
    "first_name": "Charles",
    "last_name": "Morris",
    "lat": "25.99899",
    "lng": "45.4646",
    "status": "1"

  },
  {
    "id": 6,
    "first_name": "Tracey",
    "last_name": "Ramos",
    "lat": "25.2339899",
    "lng": "45.56664646",
    "status": "1"

  }
]
};

Method

onButtonClick(data: any): void {
   alert(data.first_name + ' status is ' + data.status);
}

HTML Code

  <ng-container *ngFor="let data of dynamicData.data">
     <button [id]="data.id" class="btn btn-primary" (click)="onButtonClick(data)">
        {{data.first_name}}
     </button>
  </ng-container>

Upvotes: 3

Related Questions