From fd47a0e60dd9ab50d9f923713ca60a7fd21ccc16 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Mon, 29 Jul 2024 20:07:43 +0200 Subject: [PATCH] fix(material/radio): avoid error if destroyed quickly (#29507) Fixes an error that can happen if a radio button is destroyed before `ngAfterViewInit` has run. --- src/material/radio/radio.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/material/radio/radio.ts b/src/material/radio/radio.ts index a913374f8bc3..e4720df85265 100644 --- a/src/material/radio/radio.ts +++ b/src/material/radio/radio.ts @@ -671,7 +671,8 @@ export class MatRadioButton implements OnInit, AfterViewInit, DoCheck, OnDestroy } ngOnDestroy() { - this._inputElement.nativeElement.removeEventListener('click', this._onInputClick); + // We need to null check in case the button was destroyed before `ngAfterViewInit`. + this._inputElement?.nativeElement.removeEventListener('click', this._onInputClick); this._focusMonitor.stopMonitoring(this._elementRef); this._removeUniqueSelectionListener(); } @@ -713,7 +714,7 @@ export class MatRadioButton implements OnInit, AfterViewInit, DoCheck, OnDestroy if (!this.disabled || this.disabledInteractive) { // Normally the input should be focused already, but if the click // comes from the touch target, then we might have to focus it ourselves. - this._inputElement.nativeElement.focus(); + this._inputElement?.nativeElement.focus(); } }