Vishal Mittal
Vishal Mittal

Reputation: 366

Remove Focus from AgGrid when click outside the ag-grid

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.

Upvotes: 1

Views: 8006

Answers (3)

Chandramouli
Chandramouli

Reputation: 572

Try this option,

stopEditingWhenGridLosesFocus: true

Upvotes: 2

Sam Letts
Sam Letts

Reputation: 57

You can use the (focusout) event listener built in to angular:

In your mat-editor-one.component.html:

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

And then in your mat-editor-one.component.ts:

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

This will deselect all rows when click outside the grid.

Upvotes: 1

un.spike
un.spike

Reputation: 5113

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)

Upvotes: 3

Related Questions