Issue
Please could anyone assist. I am trying to enable a drop-down toggle in angular by creating a directive. When I use the selector in the div it does not work as expected. Using the "show" button in the drop-down class in the code below fixes the drop down items on the screen. I want to be able to toggle the class to show or hide the drop down items on click but doesn't seen to work as expected. Could anyone help out? Code below.
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
@HostBinding('class.show') isShown = false;
@HostListener('click') toggleShow(){
this.isShown = !this.isShown;
}
constructor() { }
}
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Manage Recipe
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink" appDropdown>
<a class="dropdown-item" href="#">To Shopping List</a>
<a class="dropdown-item" href="#">Edit Recipe</a>
<a class="dropdown-item" href="#">Delete Recipe</a>
</div>
</li>
</ul>
Solution
There are issues with your code and make below changes to make it work.
Apply the directive to
li
instead of the newdiv
<li class="nav-item dropdown" appDropdown>
Change the class name to
open
instead ofshow
@HostBinding("class.open") isOpen = false;
On a side note dont forget to add your directive in app.module.ts.
Sample code here - https://stackblitz.com/edit/angular-ivy-xhk538?file=angular.json
Answered By - MBB
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.