Remove Focus from AgGrid when click outside the ag-grid

偶尔善良 提交于 2020-03-05 00:22:51

问题


I'm using AG Grid on a website. When the user clicks a cell, it is focused and gets a blue outline. I need to remove this focus when the user clicks outside the selected element.

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

But this is not working when I am using mat select component in ag-grid. Example- plunker

Please change the dropdown value, the value won't change because of this.


回答1:


Ok, here what you need to understand:

  1. clicks listener should be implemented inside your custom component, cuz only withing this component you can bind listener for tracking click-outside event
  2. listener should be implemented inside ngAfterViewInit method cuz of @ViewChild rendering lifecycle
  3. @ViewChild requires to get element and his scope - for outside-click tracking possibility

So you need to have ViewChild - bound to your template (inside custom component)

@ViewChild('yourElementRef') public yourElementRef:ElementRef

Then, bound this property yourElementRef to the template (tag (div, form, whatever) should be HTML based - not directive from third party libraries - cuz reference could be missed)

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

again if you put #yourElementRef in <mat-cad> - native element reference would be missed

And the last thing is tracking itself

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

DEMO

P.S: this is a solution for selection reset ONLY, on exact this example - values (models) doesn't update properly (cuz it's just wrong implemented)



来源:https://stackoverflow.com/questions/60260806/remove-focus-from-aggrid-when-click-outside-the-ag-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!