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?