prajeesh
prajeesh

Reputation: 2382

Get selected dropdown object on edit button click - angular 4

i have a drop down that contains the list of categories

<div class="col-md-10 col-sm-10 col-xs-10 nopadding">
    <select class="form-control" [(ngModel)]="pc.profile_characteristic_category_id" name="profile_characteristic_category_id"> 
      <option value="">--Select--</option>
      <option *ngFor="let category of categories" [value]="category.profile_characteristic_category_id">{{ category.name }}</option>
    </select>
</div>

Next to the drop down is the actions button.

<div class="btn-group pull-right col-md-2 col-sm-2 col-xs-2 nopadding">
    <button type="button" class="glyphicon glyphicon-wrench action-btn" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
     </button>
     <ul class="dropdown-menu">
        <li><a data-toggle="modal" href="#addCategoryModalBox" (click)="displayNewCategoryForm()">Add</a></li>
        <li><a data-toggle="modal" href="#addCategoryModalBox" (click)="editProfileCharacteristicCategory()">Edit</a></li>
        <li><a href="#">Delete</a></li>  
    </ul>

Suppose that the drop down is having value as Category 3 and the edit button is clicked, I need to get the selected category object when the edit button is clicked.

{id: 3, 'name: Category 3', pid: 272, profile_characteristic_category_id: 1001}

Any ideas on how to implement this?

Upvotes: 0

Views: 973

Answers (2)

JB Nizet
JB Nizet

Reputation: 691805

An alternative to @trichetriche's answer is to directly use the category object itsef as the model of the select box, instead of its profile_characteristic_category_id:

<select class="form-control" [(ngModel)]="pc.selectedCategory" name="category"> 
  <option value="">--Select--</option>
  <option *ngFor="let category of categories" [ngValue]="category">{{ category.name }}</option>
</select>

The selected category object itself would now be stored in pc.selectedCategory, and you would simply have to use

(click)="editProfileCharacteristicCategory(pc.selectedCategory)"

Upvotes: 1

user4676340
user4676340

Reputation:

Well, sure, start by implementing a getter

get selectedOption() {
  return this.categories
    .find(c => c.profile_characteristic_category_id === this.pc.profile_characteristic_category_id) || null;
}

This will return the selected option, and null if the options isn't found.

Now, you can just use it with your edit button

<li><a data-toggle="modal" href="#addCategoryModalBox" (click)="editProfileCharacteristicCategory(selectedOption)">Edit</a></li>

Upvotes: 1

Related Questions