javascript - How exactly works this Angular 2 custom directive? -


i new in angular 2 , following tutorial how create custom directive , have doubts how works.

i try explain done.

i have view containing 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 can see dive having class btn-group have custom appdropdown setted on

<div     class="btn-group"     appdropdown > 

this custom directive add open class div when inner button clicked (so ul content showed bootstrap).

this code of custom directive:

import {directive, hostbinding, hostlistener} "@angular/core";  @directive({   selector: '[appdropdown]' }) export class dropdowndirective {    @hostbinding('class.open') isopen = false;    // listen click event:   @hostlistener('click') toggleopen() {     this.isopen = !this.isopen;   }  } 

from can undestood directive works in way:

1) line:

@hostbinding('class.open') isopen = false; 

bound isopen variable value of class.open attribute of div on custom directive applied.

so should mean if dive have open class setted value true, otherwise false.

is interpretation correct?

2) method:

// listen click event: @hostlistener('click') toggleopen() {   this.isopen = !this.isopen; } 

is performed when user click button in view:

  <button     type="button"     class="btn btn-primary dropdown-toggle">manage recipe <span class="caret"></span>   </button> 

ok, doubt is: why methis performed when click specific button , not when other button in page clicked?

so should mean if dive have open class setted value true, otherwise false.

it's other way round. if property isopen true class open added div. if false - removed.

is performed when user click button in view:

actually, triggered when there click on element child of element apply directive because native events bubble.

if want check button specifically, use following code:

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

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -