在外部单击时,Angular-ng-autocomplete 不会关闭下拉菜单

问题描述 投票:0回答:2

我正在尝试在我的 ionic 5 应用程序(Angular 12)中使用“angular-ng-autocomplete”(https://github.com/gmerabishvili/angular-ng-autocomplete)插件,但由于某种原因,当我点击外部时下拉列表框,它不会关闭该下拉列表。但它在 Stackblitz 示例中运行良好。

我也尝试过手动完成,但仍然不起作用。这是我的手动代码

HTML

<div class="ng-autocomplete">
  <ng-autocomplete #auto
    [data]="items"
    [searchKeyword]="keyword"
    placeholder="Name"
    (selected)='selectEvent($event)'
    debounceTime='300'
    (inputChanged)='onChangeSearch($event)'
    (inputFocused)='onFocusChanged($event)'
    [initialValue]='defaultValue'
    [itemTemplate]="itemTemplate"
    [notFoundTemplate]="notFoundTemplate">
  </ng-autocomplete>

  <ng-template #itemTemplate let-item>
    <a [innerHTML]="item.name"></a>
  </ng-template>
   
  <ng-template #notFoundTemplate let-notFound>
    <div [innerHTML]="notFound"></div>
  </ng-template> 
</div>

组件

@ViewChild('auto') auto;

  @HostListener('document:click', ['$event'])
  clickOut(event) {
      if (!event.target.attributes['autocomplete'] || event.target.attributes['autocomplete'].name !== 'autocomplete') 
      {
        this.auto.close();
      }
   }

尝试调试它,但看不出问题所在。这是一个视频 https://streamable.com/b3aowi

如有任何建议,我们将不胜感激

angular ionic-framework ionic5
2个回答
0
投票
<ng-autocomplete #auto
  [data]="items"
  [searchKeyword]="keyword"
  placeholder="Name"
  (selected)='selectEvent($event)'
  debounceTime='300'
  (inputChanged)='onChangeSearch($event)'
  (inputFocused)='onFocusChanged($event)'
  [initialValue]='defaultValue'
  [itemTemplate]="itemTemplate"
  [notFoundTemplate]="notFoundTemplate"
  (click)="$event.preventDefault()"
  >

</ng-autocomplete>

我尝试了使用 PreventDefault() 进行此事件绑定 (click)="$event.preventDefault()"

对我来说效果很好。 希望这个回答对你有帮助


0
投票
    import { ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef) {}

@HostListener('document:click', ['$event'])
onClick(event: Event) {
  const clickedInside = this.auto?.elementRef?.nativeElement.contains(event.target);
  if (!clickedInside) {
    this.auto.close(); // Close the dropdown
    this.cdr.detectChanges(); // Ensure change detection runs
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.