bootstrap 4 in Angular 2 dropdown not working

后端 未结 14 1196
旧巷少年郎
旧巷少年郎 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:35

    Example Code StackBliz Link

    Firstly Bootstrap 3 & 4 Drop down active state classes are different

    1. In Boostrap 3 : In dropdown open state; .dropdown-toggle parent element is added 'open' CSS class

    2. Where as in Boostrap 4 make use of "show" CSS class In drop down open state. Here .dropdown-toggle element's parent element and next sibling element with CSS class .dropdown-menu are added "show" css Class

    Hence to make boostrap 4 dropdown working with angular 4 we will create new angular directive class and add it to boostrap dropdown in angular template

    Step 1 - Crate new angular directive in ng-boostrap-dropdown.directive.ts

    import { Directive, HostListener, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[appNgBoostrapDropdown]'
    })
    export class NgBoostrapDropdownDirective {
    
      private isShow: boolean = false;
      private dropdownParentEl = this.elementRef.nativeElement.closest('.dropdown');
      constructor(private elementRef: ElementRef) { }
    
    
      @HostListener('click') open() {
        this.isShow = !this.isShow;
        if (this.isShow) {
          this.dropdownParentEl.classList.add('show');
          this.dropdownParentEl.querySelector(".dropdown-menu").classList.add('show');
        } else {
          this.dropdownParentEl.classList.remove('show');
          this.dropdownParentEl.querySelector(".dropdown-menu").classList.remove('show');
        }
      }
    
      @HostListener('document:click', ['$event'])
      clickout(event) {
        if (this.elementRef.nativeElement.contains(event.target) && this.isShow) {
          this.dropdownParentEl.classList.add('show');
          this.dropdownParentEl.querySelector(".dropdown-menu").classList.add('show');
        } else {
          this.dropdownParentEl.classList.remove('show');
          this.dropdownParentEl.querySelector(".dropdown-menu").classList.remove('show');
          this.isShow = false;
        }
      }
    
    }
    

    Step 2 : Import this Directive in app.module.ts

    import { NgBoostrapDropdownDirective } from './directives/ng-boostrap-dropdown.directive';
    
    @NgModule({
    
      declarations: [ AppComponent, NgBoostrapDropdownDirective ],
    
    })
    

    Step 3 : Apply directive in Template using appNgBoostrapDropdown

    NAVIGATION : 
          
            
BUTTON DROPDOWN :

Example Code StackBliz Link

提交回复
热议问题