Ravi
Ravi

Reputation: 462

Angular custome dirictive css collapse sub menu

I am following this article https://medium.com/@alok.lko631/submenu-or-dropdown-menu-without-jquery-in-angular-2-4-5-6-using-only-bootstrap-and-custom-fd716db511be for collapsing the menu and sub menu. I am able to implement the logic but the problem I am facing is that I have multiple menu and on clicking the other menu(The menu which is already opened is not getting collapsed) and also whenever I am clicking on any value of sub menu the main menu is getting collapse instead of routing ..

Stackblitz demo https://stackblitz.com/edit/angular-y3ud5q

submenu.component.html

<aside class="main-sidebar">
    <section class="sidebar">
        <ul class="sidebar-menu tree" data-widget="tree">
            <li checkToggle *ngFor="let data of listsvalue ">
                <a>
                    <span>{{data.value}}</span>
                    <span class="pull-right-container">
                        <i class="fa fa-angle-left pull-right"></i>
                    </span>
                </a>
                <ul class="nav submenu" data-widget="tree">
                    <li *ngFor="let test of data.value ">
                        <a>
                            <span>{{test.value}}</span>
                            <span class="pull-right-container">
                                <i class="fa fa-angle-left pull-right"></i>
                            </span>
                        </a>
                    </li>
                </ul>
            </li>
        </ul>
    </section>
</aside>

submenu.directive.ts

@Directive({
  selector: '[checkToggle]'
})
export class SidebarLeftToggleDirective {
  @Input('checkToggle') partner;

  /**
  * @method constructor
  * @param elementRef [description]
  */
  constructor(public elementRef: ElementRef) { }

  @HostBinding("class.active") isOpen = false;
  @HostListener("click") toggleOpen($event) {
    this.isOpen = !this.isOpen;
  }
}

submenu.component.cs

.submenu li {
    padding-left:15px;
}

ul li .submenu {
    display: none;
}

ul li.active .submenu {
    display: block;
    list-style: none;
}

Upvotes: 0

Views: 2419

Answers (1)

Vega
Vega

Reputation: 28738

The solution could be mush easier with inline statement and class attibute than Hostbinding in the directive, as it allows to track only one line.

You just need to track a property that will hold the current opened li index, the class "active" would be then assigned only on that condition:

<li [class.active]="opened==i" *ngFor="let innerData of partner.value | keyvalue;let i=index" (click)="opened=opened==i?-1:i">

This way, any time there is a click, the evaltion of the property will switch between classes and make the "li"s opened or collapsed

Demo

Upvotes: 1

Related Questions