【问题标题】:Kendo Popup undefined anchor剑道弹出未定义锚点
【发布时间】:2022-01-08 10:41:12
【问题描述】:

我在实现 Kendo UI 弹出窗口的点击离开功能时遇到了一些问题,如下所述:https://www.telerik.com/kendo-angular-ui/components/popup/closing/

我的代码流程是用于实际过滤器弹出窗口的 [anchor] 是在容器中定义的。尽管如此,我确信这不是问题的一部分。我的组件文件(相关部分):

@ViewChild("anchor", { read: ElementRef}) public anchor: ElementRef;
    @ViewChild("popup", { read: ElementRef }) public popup: ElementRef;

    @HostListener("keydown", ["$event"])
    public keydown(event: any): void {
        if (event.keyCode === 27) {
        this.onToggle(false);
        }
    }

    @HostListener("document:click", ["$event"])
    public documentClick(event: any): void {
        if (!this.contains(event.target)) {
        this.onToggle(false);
        }
    }

private contains(target: any): boolean {
        return (
          this.anchor?.nativeElement?.contains(target) ||
          (this.popup ? this.popup.nativeElement.contains(target) : false)
        );
      }
public onToggle(show? : boolean): void {
        this.show = show ?? !this.show;
    }

HTML:

<button  #anchor (click)="onToggle()" mat-raised-button color="list-button">
    <div fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="10px">
        <fa-icon [icon]="faFilter" class="fa-sm"></fa-icon>
        <div>Filter</div>
    </div>
</button>
<div class="kendo-override-popup mimick-material-popup">
    <kendo-popup #popup [popupAlign]="popupAlign" [anchorAlign]="anchorAlign"
        [anchor]="inputAnchor" [type]="slide" [margin]="margin" *ngIf="show">   

...

问题归结为单击按钮正确触发了切换,但是文档单击事件随后触发,并且它始终为包含返回 false,因此它也会自动关闭下拉列表。我运行了 kendo 在 stackblitz 中的示例,并且他们的视图子元素存在得很好,对我来说,无论我放在哪里,锚始终是未定义的,或者我是否读取了元素 ref

【问题讨论】:

    标签: angular kendo-ui


    【解决方案1】:

    在浏览和查看与未定义的 ViewChildren 相关的其他 SO 问题后,我遇到了针对我的问题的解决方案:

    1. 将整个组件包装在div
    2. 给该 div 一个标识符,例如:#wrapper
    3. 更新代码如下:

    @ViewChildren("wrapper") 公共包装器:任意;

    private contains(target: any): boolean {
    
            let button = this.wrapper?.first?.nativeElement?.children[0] as HTMLButtonElement;
    
            return (
               button.contains(target) ||
              //this.anchor?.nativeElement?.contains(target) ||
              (this.popup ? this.popup.nativeElement.contains(target) : false)
            );
          }
    

    这是可行的,因为我们知道我们的 html 布局是什么样的,因此我们非常确定 element[0] 是一个 html 按钮元素。这不是最漂亮的方法,但它有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      相关资源
      最近更新 更多