问题
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:
- clicks
listener
should be implemented inside your custom component, cuz only withing this component you can bind listener for tracking click-outside event listener
should be implemented insidengAfterViewInit
method cuz of@ViewChild
rendering lifecycle@ViewChild
requires to getelement
and hisscope
- 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