角度下拉导航

时间:2017-08-01 13:08:15

标签: javascript angular typescript angular2-directives

我正在尝试使用下拉导航以这种方式创建复杂的面包屑

enter image description here

我正在努力解决外部点击问题:当我需要关闭下拉菜单点击某个地方时,如果我点击另一个导航项目 - 它应该是打开的(有只有一个同时打开的面包屑。)

我这样做了:

1)我通过在父元素

中包含event.target来检测outsideClick

2)通过关闭所有面包屑并打开所需的面包屑来进行切换。

simple example of breadcrumbs Plunker

时间表:

     <ul #simpleBreadcrumbs>

      <li *ngFor="let breadcrumb of breadcrumbs"
        class="bread_item"
        (click)="toogleStateOfSubparagraphs(breadcrumb)">

        <div>
          <span>{{breadcrumb.label}}</span>
          <i class="icon-arrows-glyph-1_bold-down"
             *ngIf="!breadcrumb.isOpen">
          </i>
          <i class="icon-arrows-glyph-1_bold-up"
             *ngIf="breadcrumb.isOpen">
          </i>
        </div>


        <ul class="switcher__list dropdown__list"
            *ngIf="breadcrumb.isOpen">
          <li class="switcher__item dropdown__item" *ngFor="let subparagraph of breadcrumb.subparagraphs">
            <a class="switcher__item-href">
              {{subparagraph.label}}
            </a>
        </li>
    </ul>

  </ul>

组件类:

export class App {
  breadcrumbs:any[];

  @ViewChild('simpleBreadcrumbs') private _breadcrumbsTemplate: ElementRef;
  _currentOpenedBreadcrumbs:any;

  constructor() {
    this.breadcrumbs = [
      {
        label: 'First',
        isOpen: false,
        subparagraphs: [
          {
            label: '1.1'
          },
          {
            label: '1.2'
          }]
      },
      {
        label: 'Second',
        isOpen: false,
        subparagraphs: [
          {
            label: '2.1'
          },
          {
            label: '2.2'
          }]
      }];
  }

  toogleStateOfSubparagraphs(breadcrumb) {
     if (this._currentOpenedBreadcrumbs === breadcrumb) {
      this._closeSubparagraphs();
      this._currentOpenedBreadcrumbs = null;
      return;
    }
    this.breadcrumbs
      .forEach((bread: IBreadCrumb) => {
        bread.isOpen = false;
        if (bread === breadcrumb) {
          bread.isOpen = true;
        }
      });
    this._currentOpenedBreadcrumbs = breadcrumb;
  }

  _closeSubparagraphs() {
    this.breadcrumbs
      .map((bread) => {
        bread.isOpen = false;
        return bread;
      });
  }

  @HostListener('window:keydown', ['$event'])
  public onEscapeClick(event: KeyboardEvent): void {
    if (event.which === 27 && !this._breadcrumbsTemplate.nativeElement.contains(event.target as Node)) {
      this._closeSubparagraphs();
    }
  }

  @HostListener('document:click', ['$event'])
  public onOutsideClick(event: Event): void {
   if (!this._breadcrumbsTemplate.nativeElement.contains(event.target as Node)) {
      this._closeSubparagraphs();
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我将您的CSS文件更改为:

.bread_item {
 list-style: none;
 float: left;
 padding: 30px;

}

这是你在找什么? 如果没有,我可能会误解你的问题。

你之前的css使得第二个元素在点击第一个元素时也被按下了。