skip to Main Content

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?

2

Answers


  1. You can use @for for running the loop and using @if with as syntax, to create the display label and reuse it for both the function and the label!

    Angular Control Flow Syntax

    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <ul class="dropdown-menu">
          @for(i of arr;track $index) {
          <li>
            @if(i?.toString()?.padStart(2);as displayName) {
            <a class="dropdown-item" href="#" (click)="getMyValue('myval' + i, displayName)">My Value {{displayName}}</a>
            }
          </li>
          }
        </ul>
      `,
    })
    export class App {
      name = 'Angular';
      arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
      getMyValue(todo: string, displayName: string) {
        console.log('selected value is:', todo);
        console.log('selected text is:', displayName);
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search