【问题标题】:Angular dropdown toggle and closeOutside角度下拉切换和 closeOutside
【发布时间】:2019-03-29 12:09:57
【问题描述】:

我正在开发一个有几个点击事件的导航组件,我需要你的帮助:)

在我的html中我有

<ul class="nav-right">
<li (click)="toggleDropdown('item1')" (clickOutside)="clickEvent($event)">
  <span class="selector">
    my Selector
  </span>

  <ul *ngIf="isActive('item1')">
    <li *ngFor="let value of values">
          {{city.name}}
    </li>
  </ul>
</li>

<li (click)="toggleDropdown('other')" (clickOutside)="clickEvent($event)">
  <span class="selector">
    Other
  </span>
  <ul *ngIf="isActive('other')">
    <li *ngFor="let otherValue of otherValues">
        {{otherValue.name}}
    </li>
  </ul>
</li>

然后在我的组件中,我有几个事件可以在组件之间切换

toggleDropdown(menu: any) {
   this.activeMenu = this.activeMenu === menu ? 0 : menu;
}

isActive(menu: string): boolean {
  return this.activeMenu === menu;
}

最后我使用指令来检测导航之外的点击

@Directive({ selector: '[clickOutside]' })
export class ClickOutsideDirective {
@Output() clickOutside = new EventEmitter<MouseEvent>();

constructor(private elementRef: ElementRef) { }

@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent): void {
const targetElement = event.target as HTMLElement;

if (targetElement && !this.elementRef.nativeElement.contains(targetElement)) {
  this.clickOutside.emit(event);
    }
  }
}

我的问题是我不知道如何检查单击的项目是否需要打开,因为我单击了项目本身。我认为那些事件崩溃了,但我不知道如何解决它,如果您能给我提示,我将不胜感激。

提前致谢!

【问题讨论】:

    标签: javascript angular angular2-directives


    【解决方案1】:

    所以我找到了一个非常简单的解决方案,我将在此处发布以供将来的自己使用,以防有人发现它有用。这只是改变某些元素的位置的问题

    (clickOutside)="clickEvent($event)"
    

    <ul class="nav-right">
    

    所以最后我的html标记是:

    <ul class="nav-right" (clickOutside)="clickEvent($event)">
      <li (click)="toggleDropdown('item1')">
        <span class="selector">
         my Selector
        </span>
    
      <ul *ngIf="isActive('item1')">
         <li *ngFor="let value of values">
          {{city.name}}
        </li>
      </ul>
    </li>
    
     <li (click)="toggleDropdown('other')">
       <span class="selector">
         Other
       </span>
       <ul *ngIf="isActive('other')">
         <li *ngFor="let otherValue of otherValues">
           {{otherValue.name}}
         </li>
       </ul>
     </li>
    </ul>
    

    因为我想要实现的是当有人在导航栏外点击时关闭所有下拉菜单

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      相关资源
      最近更新 更多