简体   繁体   中英

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 (eg using ngModal ) ?

Please help and guide.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM