gaurav soni gaurav soni - 2 months ago 11
HTML Question

Prevent host listener to call two times on div inside label

I have an div element wrapped with label tag. Label tag has checkbox element. When I get click event value from my directive(by hostListener), my
directive called two times one on div inside label and other for checkbox. How can I call my directive exactly one time.

My directive

import { Directive, HostListener } from '@angular/core';

@Directive({
selector: '[home]'
})
export class HomeDirective {
@HostListener('click', ['$event.target']) onclick(data: any) {
console.log(data);
}
}


My html,

<div>
<label for="test">
<div home>test dataa
<input type="checkbox" id="test" />
</div>
</label>
</div>


Output when click on div with home directive:-

enter image description here

Answer

The problem is when you click on "Test data", this triggers directive click event(1st directive click). This text is part of label. When you click at label, item specified in "for" tag will be clicked( 2nd directive click).

To prevent double firing you should move text from div.

<div>
 <label for="test">
   test dataa
   <div home>
   <input type="checkbox" id="test" />
  </div>
 </label>
</div>

http://plnkr.co/edit/TyxkmhLlvKszXYarXXvr?p=preview

Comments