【问题标题】:Dropdown menu to clicking outside close of Angular 8单击 Angular 8 外部关闭的下拉菜单
【发布时间】:2020-02-06 06:21:25
【问题描述】:

嗨,我在p 标签上使用click 函数,

当用户打开下拉菜单时,在外部单击时以角度关闭下拉菜单

HTML代码

<div class="select_cat">
   <p class="cat_name" (click)="openCategoriesList()"> </p>
</div>
<div class="categories_list" *ngIf="openCategories">
   <ul *ngFor="let category of categories"> 
      <span class="title">{{category.group_name}}
      </span> 
      <li *ngFor="let categoryData of category.categories" (click)="categoryClick(categoryData)"> 
      </li> 
   </ul>
</div>

【问题讨论】:

  • Html 代码

      {{category.group_name}}
  • 你能提供你写的代码或提供一个最小的例子小提琴

标签: html angular


【解决方案1】:

使用(文档:点击)事件:

.html 代码

<div class="select_cat" #paraDiv> /* Created a reference here */
   <p class="cat_name" (click)="openCategoriesList()">Open CategoryList</p>
</div>
<div class="categories_list" *ngIf="openCategories">
   <ul *ngFor="let category of categories"> 
      <span class="title">{{category.group_name}}
      </span> 
      <li *ngFor="let categoryData of category.categories" (click)="categoryClick(categoryData)"> 
      </li> 
   </ul>
</div>

.ts 代码

@Component({
  host: {
    '(document:click)': 'onDocumentClick($event)',
  }
})

@ViewChild('paraDiv', {static: false}) paraDiv;

onDocumentClick(event) {
   if (!this.paraDiv.nativeElement.contains(event.target)) { // outside click
     this.openCategories = false;
   }
}

【讨论】:

  • 嗨 Gangadhar,我在 formarray 中使用多个复选框来处理反应表单,如何在提交后重置值
【解决方案2】:
 <mat-select #mySelect placeholder="Favorite food">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{ food.viewValue }}
    </mat-option>
  </mat-select>

   import {Component, ViewChild} from '@angular/core';

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
  @ViewChild('mySelect') mySelect;
  foods = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];

  click() {
    this.mySelect.open();
  }
}

【讨论】:

  • 嗨 Akash,在 html 页面中使用的点击功能
  • 我觉得现在很容易
  • 对不起,我想要使用点击功能是 P 标签这种类型,当用户打开下拉菜单时,点击外部关闭下拉菜单
  • 调用关闭函数一样
  • 嗨,Akash 有一个小疑问,请向我建议
猜你喜欢
  • 1970-01-01
  • 2023-02-23
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多