user1468867
user1468867

Reputation: 61

Accessing a clicked element's data source for a custom select in Angular 2

I am trying to build a custom select in Angular 2 made of html. The idea is that when a user clicks an item in the options the main label of the dropdown updates to reflect which one is selected. So far I have the following code:-

HTML:-

<div class="dropdown">
    <div>
        <span>Type: <strong>{{typeDropdown.label}}</strong></span>
    </div>
    <div class="options">
        <div *ngFor="let item of typeDropdown.options" [attr.data-label]="item.label" [attr.data-value]="item.value" (click)="selectDropdownItem($event)">{{item.label}}</div>
    </div>
</div>

TS File:-

typeDropdown:any = { 
    label: 'Any', 
    value: 'any', 
    options: [
        { label: 'Type 1', value: '1' },
        { label: 'Type 2', value: '2' },
        { label: 'Type 3', value: '3' }
    ]
}

selectDropdownItem(event){
    let t = event.target;
    this.typeDropdown.label = t.getAttribute('data-label');
}

Rather than doing "this.typeDropdown.label" I want to access the actual data source so that it is dynamic. So for example if I had another dropdown that was populated by a different array the same click function could be applied to that so essentially something like:-

this.<data source of clicked element goes here>.label = t.getAttribute('data-label');

Is this possible?

Upvotes: 0

Views: 203

Answers (1)

Emerceen
Emerceen

Reputation: 2885

You can pass item to the method "selectDropdownItem", and set selectedItem

HTML:-

<div class="dropdown">
  <div>
    <span>Type: <strong>{{selectedItem.label}}</strong></span>
  </div>
  <div class="options">
    <div *ngFor="let item of typeDropdown.options (click)="selectDropdownItem(item)">{{item.label}}
  </div>
</div>

TS File:-

typeDropdown:any = {
  options: [
    { label: 'Type 1', value: '1' },
    { label: 'Type 2', value: '2' },
    { label: 'Type 3', value: '3' }
  ]
}

selectedItem: any {
  label: '',
  value: ''
}

selectDropdownItem(item: any): void {
  this.selectedItem = item;
}

Upvotes: 0

Related Questions