8

I am using Angular 6.0.5 alongside with Bootstrap 4.1.1 and I added a directive for dropdowns. But I can't make it work in no way. I have seen a lot of similar problems here but none was for Bootstrap 4. this is the dropdown html:

<div class="btn-group" appDropdown>
  <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
    Manage
    <span class="caret"></span></button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" style="cursor: pointer"
           (click)="OnAddToShoppingList()">To Shopping List</a></li>
    <li><a class="dropdown-item" href="#">Edit Recipe</a></li>
    <li><a class="dropdown-item" href="#">Delete Recipe</a></li>
  </ul>
</div>

and this is the directive:

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

@Directive({
  selector: '[appDropdown]'
})
export class DropdownDirective {
  @HostBinding('class.open') isOpen = false;

  @HostListener('click') toggleopen() {
    this.isOpen = !this.isOpen;
  }
}

I suspected about the "open" class. and I think it was a depreacted class from Bootstrap 3. so what is alternative in Bootstrap 4?

2
  • 1
    bootstrap 4 using show class change your open class to show Commented Jul 9, 2018 at 15:35
  • @ChellappanV I tried show but it's not working Commented Jul 10, 2018 at 3:40

2 Answers 2

20

In order to work drop down in bootstrap you need to add show class in two places which you can achieve by get the reference to isOpen variable using angular template ref

If you want to get the reference to directives you need to export the directive first

@Directive({
  selector: '[appDropDown]',
exportAs:'appDropDown'
})

Then you can use the template ref method to achive dropdown

<div class="btn-group" appDropDown #r="appDropDown" >
  <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" >
    Manage
    <span class="caret"></span></button>
  <ul class="dropdown-menu" [ngClass]="{'show':r.isOpen}" >
    <li><a class="dropdown-item" style="cursor: pointer"
           >To Shopping List</a></li>
    <li><a class="dropdown-item" href="#">Edit Recipe</a></li>
    <li><a class="dropdown-item" href="#">Delete Recipe</a></li>
  </ul>
</div>

I have include example here check out: https://stackblitz.com/edit/angular-h9rgmn

Sign up to request clarification or add additional context in comments.

2 Comments

Did you create a local reference on a directive and then used the current value from the attribute in the directive in ngClass?
Yes binding appdropdown attributes to ng lass
1

Make sure you have imported your directive to app.module.ts file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.