how to make function for entire html class in angular

is there a chance to make function for whole class, not to add it to each line. in my case class="dropdown-item" for each link with this class i want to have same function

 <li class="nav-item dropdown primary">
          <a class="nav-link links-bar" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Eyes
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a *class="dropdown-item" (click)="selectChangeLink($event)"* id="14">Eye Pencil</a>
            <a class="dropdown-item" (click)="selectChangeLink($event)" id="13">Mascara</a>
            <a class="dropdown-item" (click)="selectChangeLink($event)" id="12">Eye Brow</a>
            <a class="dropdown-item" data-value="4">Eye Lashes</a>
            <a class="dropdown-item" data-value="5">Eye Liner</a>
            <a class="dropdown-item" data-value="6">Eye Shadow</a>

>Solution :

You can use a directive. If the selector of the directive is in the way .className it’s applied to all the elements with this directive. e.g. (*)

@Directive({
  selector:'.dropdown-item'
})
export class DropDownItemDirective{
  @HostListener('click',['$event']) click(event:any){
    console.log(this.elementRef.nativeElement.getAttribute("data-value"))
    //or 
    console.log(event)
  }
constructor(private elementRef:ElementRef){}
}

But, any way. You can also use an array variable and use *ngFor in your app, some like

dataArray=[{id:14,label:'Eye Pencil'},{id:13,label:'Mascara',{id:12,label:'Eye brow']

<a *ngFor="let item of dataArray" 
   class="dropdown-item" (click)="selectChangeLink($event)" 
   [id]="item.id">{{item.label}}</a>

(*)Don’t forget import in your module

Leave a Reply