ganesh
ganesh

Reputation: 474

Angular 12: ERROR TypeError: Cannot read properties of undefined (reading 'nativeElement')

I have phone number input field in which I have attached prefixes dropdown. Below is code for that.

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");
  }

Above code works fine on page but its giving error like ERROR TypeError: Cannot read properties of undefined (reading 'nativeElement') when I use above code on modal.

When modal opens prefix dropdown is not working and showing that error.

How should I resolve above error? Is there any alternative way to do this (e.g. using ngModal) ?

Please help and guide.

Upvotes: 0

Views: 5196

Answers (1)

Lipin
Lipin

Reputation: 9

This is because the DOM not loaded completely when the openPrefixes() & closePrefixes() happens. Implement AfterViewInit and run the code inside.

ngAfterViewInit() {
     this.renderer.addClass(this.prefixes.nativeElement, "active");
  }

Upvotes: 1

Related Questions