1
votes

I am very new in Angular 2 and I am following a tutorial about how to create a custom directive and I have some doubts about how it exactly works.

I will try to explain what it was done.

I have a view containing something like this:

<div class="row">
  <div class="col-xs-12">
    <div
      class="btn-group"
      appDropDown
     >
      <button
        type="button"
        class="btn btn-primary dropdown-toggle">Manage Recipe <span class="caret"></span>
      </button>

      <ul class="dropdown-menu">
        <li><a href="#">To Shopping List</a></li>
        <li><a href="#">Edit Recipe</a></li>
        <li><a href="#">Delete Recipe</a></li>
      </ul>
    </div>
  </div>
</div>

As you can see this dive having class btn-group have my custom appDropDown setted on

<div
    class="btn-group"
    appDropDown
>

This custom directive simply add the open class to this div when the inner button is clicked (so the UL content is showed by BootStrap).

This is the code of my custom directive:

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

@Directive({
  selector: '[appDropDown]'
})
export class DropDownDirective {

  @HostBinding('class.open') isOpen = false;

  // listen to a click event:
  @HostListener('click') toggleOpen() {
    this.isOpen = !this.isOpen;
  }

}

From what I can undestood this directive works in this way:

1) This line:

@HostBinding('class.open') isOpen = false;

bound the isOpen variable to the value of the class.open attribute of the div on which my custom directive is applied.

So it should mean that if this dive have the open class setted the value will be true, otherwise will be false.

Is it this interpretation correct?

2) This method:

// listen to a click event:
@HostListener('click') toggleOpen() {
  this.isOpen = !this.isOpen;
}

is performed when the user click this button in the view:

  <button
    type="button"
    class="btn btn-primary dropdown-toggle">Manage Recipe <span class="caret"></span>
  </button>

Ok, now my doubt is: why this methis is performed only when I click this specific button and not when any other button in my page is clicked?

1

1 Answers

1
votes

So it should mean that if this dive have the open class setted the value will be true, otherwise will be false.

It's actually the other way round. If the property isOpen is true the class open will be added to the div. If false - removed.

is performed when the user click this button in the view:

Actually, it will be triggered when there is a click on any element that is the child of the element to which you apply a directive because native events bubble.

If you want to check for the button specifically, use the following code:

  @HostListener('click', ['$event.target'])
  clicked(element) {
    if (element.classList.contains('dropdown-toggle')) {
      console.log('button clicked');
    }
  }