【问题标题】:Remove Focus from AgGrid when click outside the ag-grid在 ag-grid 外部单击时从 AgGrid 中删除焦点
【发布时间】:2020-06-01 06:55:18
【问题描述】:

我在网站上使用 AG Grid。当用户单击一个单元格时,它会聚焦并获得一个蓝色轮廓。 当用户在所选元素之外单击时,我需要移除此焦点。

const body = document.body;
body.addEventListener('mouseup', (e) => {
    const container = this.commonAgGrid.nativeElement;
    if (!container.contains(e.target)) {
        this.gridApi.clearFocusedCell();
    }
 });

但是当我在 ag-grid 中使用 mat select 组件时,这不起作用。示例-plunker

请更改下拉列表的值,该值不会因此而改变。

【问题讨论】:

    标签: angular ag-grid ag-grid-angular


    【解决方案1】:

    好的,这里你需要了解:

    1. 点击listener应该在你的自定义组件中实现,因为只有这个组件你可以绑定监听器进行跟踪 点击外部事件
    2. listener 应该在 ngAfterViewInit 方法内实现,因为 @ViewChild 渲染生命周期
    3. @ViewChild 需要获取 element 和他的 scope - 用于外部点击跟踪的可能性

    所以您需要将ViewChild - 绑定到您的模板(在自定义组件内)

    @ViewChild('yourElementRef') public yourElementRef:ElementRef
    

    然后,将此属性yourElementRef 绑定到模板(标签(div、form、whatever)应该是基于 HTML 的 - 不是来自第三方库的指令 - 因为可能会丢失参考)

    template: `
        <mat-card>
        <form #yourElementRef class="container" tabindex="0" (keydown)="onKeyDown($event)">
        ...
    

    再次,如果您将 #yourElementRef 放入 &lt;mat-cad&gt; - 将错过原生元素引用

    最后一件事就是跟踪自己

    ngAfterViewInit() {
        ...
        let body = document.body;
            body.addEventListener("mouseup", (e) => {
            let container = this.yourElementRef.nativeElement;
            if (!container.contains(e.target)){   
                this.params.api.clearFocusedCell();
            }
        })
    }
    

    DEMO

    PS:这是selectionreset ONLY的解决方案,在这个例子中 - 值(模型)没有正确更新(因为它只是错误地实现了)

    【讨论】:

    • 好的。这意味着我必须在每个自定义组件中写这个ngAfterViewInit() { ... let body = document.body; body.addEventListener("mouseup", (e) =&gt; { let container = this.yourElementRef.nativeElement; if (!container.contains(e.target)){ this.params.api.clearFocusedCell(); } }) }?关于值(模型)没有正确更新 - 我从 Ag-Grid 演示站点选择了这个例子,所以你能告诉我我该如何解决这个问题吗?
    • 再次模型绑定有点出问题了,新建一个xD
    【解决方案2】:

    您可以使用 angular 内置的 (focusout) 事件监听器:

    在您的 mat-editor-one.component.html 中:

    <ag-grid-angular #commonGrid style="width: 100%; height: 450px;" class="ag-theme-material"
                 [gridOptions]="gridOptions"
                 (focusout)="focusOut()"
                 [modules]="modules">
    

    然后在你的 mat-editor-one.component.ts 中:

    focusOut () {
    this.gridApi.deselectAll()
     }
    

    当在网格外单击时,这将取消选择所有行。

    【讨论】:

    • 这不起作用。 (focusout) 绑定在网格内部和外部的每次单击时都会调用,并且 gridApi.deselectAll() 仅取消选择行,而不是 OP 要求的正在编辑的单元格。 @un.spike 的答案有正确的 api 调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2012-07-05
    • 1970-01-01
    • 2018-05-29
    • 2023-01-26
    • 1970-01-01
    相关资源
    最近更新 更多