Within my phone number input field, I have integrated a prefixes dropdown. Below is the code snippet for this feature.
HTML code in modal
<div
class="phone"
[ngClass]="{ 'error_border': submitted && f.phoneNumber.errors }"
>
<div class="phone__select">
<span class="phone__prefix" (click)="openPrefixes()"
>{{ selectedPrefix }}</span
>
<ul #prefixes class="prefixes">
<li
*ngFor="let prefix of availablePrefixes"
class="prefix"
(click)="prefixChange(prefix)"
>
{{ prefix }}
</li>
</ul>
</div>
<input
class="phone__input form-control"
maxlength="13"
type="text"
pattern="^(?!0+$)\d{10,}$"
formControlName="phoneNumber"
/>
</div>
TS
@ViewChild("prefixes") prefixes!: ElementRef;
selectedPrefix = "+43";
availablePrefixes = ["+43", "+49"];
prefixChange(prefix: string): void {
this.selectedPrefix = prefix;
this.closePrefixes();
}
openPrefixes(): void {
this.renderer.addClass(this.prefixes.nativeElement, "active");
}
closePrefixes(): void {
this.renderer.removeClass(this.prefixes.nativeElement, "active");
}
The code displayed above functions correctly on the page but throws an error
ERROR TypeError: Cannot read properties of undefined (reading 'nativeElement')
when implemented within a modal.
Upon opening the modal, the prefix dropdown fails to work and displays the aforementioned error message.
Is there a way to resolve this error? Are there alternative methods to achieve the same result (e.g. utilizing ngModal
) ?
Your assistance and guidance would be greatly appreciated.