Issue
I am seeing odd behavior with element referencing:
I have a button that triggers mat-menu, which, in turn, opens a dialog. To get the focus back from the dialog to the original button, I pass the button as an element reference via @ViewChild to the component. After the dialog is closed (on subscribe) I attempt to refocus on the button but no action happens because the element is not in the DOM. If I manually query the button via document.getElementById() and then set the focus then everything works. I printed both versions and they seem the same but when compared via === they evaluate to false.
TS
@Component({
...
})
export class MyClass {
@ViewChild('myButton', {read: ElementRef, static: false})
myButton?: ElementRef;
...
onButtonAction() {
const myDialogRef = this.dialogRef.open(MyDialog);
myDialogRef.afterClosed().subscribe(() => {
this.myButton?.nativeElement?.focus(); // doesn't work
document.getElementById('myCoolButton')?.focus(); // works
});
}
HTML
<mat-menu #myMenu="matMenu">
<button mat-menu-item
(click)="onButtonAction()">
Open dialog
</button>
</mat-menu>
<button mat-icon-button
type="button"
id="myCoolButton"
#myButton
[matMenuTriggerFor]="myMenu"
(click)="$event.stopPropagation()">
<mat-icon>more_vert</mat-icon>
</button>
Why is this happening, and is there a better way to accomplish what I want.
Edit: It turns out this is happening due to re-rendering of the button. The component that holds the button and mat-menu gets reconstructed every time the dialog is opened. I currently have no way (and still looking for a way) to avoid this re-construct.
Solution
The reference was lost due to reconstructing the component every time the dialog was opened. The whole row was re-rendered, and so adding trackBy to the rows solved the issue.
Answered By - PolinaGo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.