bootstrap 4 in Angular 2 dropdown not working

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

    Inspired by Rahul Talar's first version(Step 1 - Crate new angular directive in ng-boostrap-dropdown.directive.ts), i've made some similar using Rendere2

    import { Directive, HostListener, ElementRef, Renderer2, OnInit } from '@angular/core';
    
    @Directive({
      selector: '[appDropdown]'
    })
    export class AppDropdownDirective implements OnInit {
      private isShow = false;
      private classShow = 'show';
      private parentNode: HTMLElement;
      private siblingNode: HTMLElement;
    
      constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
    
      ngOnInit() {
        this.parentNode = this.renderer.parentNode(this.elementRef.nativeElement);
        this.siblingNode = this.renderer.nextSibling(this.elementRef.nativeElement);
      }
    
      @HostListener('click') open() {
        this.isShow = !this.isShow;
        if (this.isShow) {
          this.addClass();
        } else {
          this.removeClass();
        }
      }
    
      @HostListener('document:click', ['$event']) clickout(event) {
        if (this.elementRef.nativeElement !== event.target && this.isShow) {
          this.removeClass();
          this.isShow = false;
        }
      }
    
      private addClass() {
        this.renderer.addClass(this.parentNode, this.classShow);
        this.renderer.addClass(this.siblingNode, this.classShow);
      }
    
      private removeClass() {
        this.renderer.removeClass(this.parentNode, this.classShow);
        this.renderer.removeClass(this.siblingNode, this.classShow);
      }
    }
    

提交回复
热议问题