Search code examples
angularevent-handlingonclicklistenerangular5angular-directive

Angular5 use Hostlistener and directive to highlight selected row


Using Angular 5/2, I have created a table that pulls values from an array that exists in my TS file called "levels".

My HTML:

<table class="table table-bordered table-condensed table-hover">
  <thead>
    <tr>
      <th class="text-center">
        <input type="checkbox" name="all" />
      </th>
      <th>Level</th>
      <th>Time</th>
      <th>Hourly Rate</th> 
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let level of levels ; let i = index">
      <td class="text-center">
         <input type="checkbox" 
          value="{{level.id}}"
          appHighlightOnCheck"/>
      </td>
      <td class="text-center">{{ level }}</td>
      <td>
         <input
         type="text"
         class="form-control">
      </td>
      <td>
         <input
         type="text"
         class="form-control">
       </td>
    </tr>
  </tbody>
</table>

When a checkbox is checked for a particular row, I want that row to have the class active, so it is highlighted.

Directive:

import { Directive, ElementRef, OnInit, Renderer2, HostListener } from "@angular/core";

@Directive({
    selector: '[appHighlightOnCheck]'
})
export class HighlightOnCheck implements OnInit{
    constructor(private renderer: Renderer2, private elementRef: ElementRef){}

    ngOnInit(){console.log(this.elementRef.nativeElement.parentNode.parentNode);

        if(this.elementRef.nativeElement.isChecked){
            this.renderer.addClass(this.elementRef.nativeElement.parentNode.parentNode, 'active');  
        }
    }
}

isChecked doesn't seem to be the correct method. I have tried to implement other people's answers, but, being new to Angular 5 I am struggling.


Solution

  • this can be done without directive. see if this helps:

    <tbody> <tr *ngFor="let level of levels ; let i = index" [class. active]="level.check?true:null"> <td class="text-center"> <input type="checkbox" value="{{level.id}}" (change)="level.check = $event.target.checked"/> </td> <td class="text-center">{{ level }}</td> <td> <input type="text" class="form-control"> </td> <td> <input type="text" class="form-control"> </td> </tr> </tbody>