bootstrap 4 in Angular 2 dropdown not working

后端 未结 14 1192
旧巷少年郎
旧巷少年郎 2021-02-04 08:36

I have followed the following to install bootstrap 4 into my Angular 2 project: Accepted Answer, following the first 1,2,3 and 4 steps

However when I add the following <

14条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 09:23

    With Angular 8 and Bootstrap 4.2 this is the working solution I'm using :

    1- First I've created a custom directive. What it does is listen to the on click event of the dropdown container and toggle the .show class of the .dropdown-menu element (Bootstrap 4 standard behavior). Also, it will close the dropdown menu if there's a click everywhere else on the document.

    import {Directive, ElementRef, HostBinding, HostListener, OnInit} from '@angular/core';
    
    @Directive({
      selector: '[appDropdown]'
    })
    export class DropdownDirective implements OnInit {
      dropDownMenu: HTMLElement;
      @HostListener('document:click', ['$event']) toggleOpen(event: Event) {
        if ( this.dropDownButton.nativeElement.contains(event.target) ) {
          this.dropDownMenu.classList.toggle('show');
        } else {
          this.dropDownMenu.classList.remove('show');
        }
      }
    
      constructor(private dropDownButton: ElementRef) { }
    
      ngOnInit(): void {
        this.dropDownMenu = this.dropDownButton.nativeElement.querySelector('.dropdown-menu');
      }
    }
    

    2- Once your directive is created and registered. Be sure to apply the directive to the dropdown element, like on this example:

提交回复
热议问题