Search code examples
htmlangulartypescripttwitter-bootstrapdropdown

Getting the inner HTML value from the dropdown


I am using a Bootstrap dropdown like this:

<ul class="dropdown-menu">
  <li>
    <a class="dropdown-item" href="#" (click)="getMyValue('myvalue')">My Value</a>
  </li>
  <li>
    <a class="dropdown-item" href="#" (click)="getMyValue('someothervalue')">Some Other Label</a>
  </li>
 </ul>

and the function looks like this:

getMyValue(todo: string) {
  console.log("selected value is:", todo);
  console.log("selected text is:", ???);
}

Instead of parsing the text as the second parameter like "My Value 01", "02" etc. Is there any way I can omit this and use it smart so I don't need to write the same things several times?


Solution

  • You can pass the event to your method.

    <li>
      <a class="dropdown-item" href="#" (click)="getMyValue('myval1', $event)"
        >My Value 01</a>
    </li>
    <li>
      <a class="dropdown-item" href="#" (click)="getMyValue('myval2', $event)"
        >My Value 02</a>
    </li>
    

    And retrieve the label with event.target.value.

    getMyValue(todo: string, event: any) {
      console.log('selected value is:', todo);
      console.log("selected text is:", event.target.text);
    }
    

    Alternatively, you may consider working with an array to generate the HTML elements.

    So you can pass each item element to the method during click event.

    items = [
      { value: 'myval1', label: 'My Value 01' },
      { value: 'myval2', label: 'My Value 02' },
    ];
    
    getMyValue(item: any) {
      console.log('selected value is:', item.value);
      console.log('selected text is:', item.label);
    }
    
    <li *ngFor="let item of items">
      <a class="dropdown-item" href="#" (click)="getMyValue(item)"
      >{{item.label}}</a>
    </li>
    

    Demo @ StackBlitz