How to pass reference of element which is added to DOM on certain condition being true?

47 Views Asked by At

I am trying to use Enter key Press event in my angular code where I am passing previous and next element reference to method ,but one element is added to DOM if user fulfill the condition, and so as it added after condition is being true , how can i pass element reference to method beforehand

//this snippet is from my code in component.ts

onEnterKeyPress1(
    event: KeyboardEvent,
    nextInputElement: HTMLInputElement | HTMLSelectElement,
    previousInputElement:HTMLInputElement | HTMLSelectElement
  ): void 
{
    if (event.key === 'Enter' || event.key === 'ArrowDown') {
      event.preventDefault();
      this.focusNextVisibleElement1(nextInputElement)
    } else if( event.key === 'ArrowUp'|| event.key === 'Backspace')
    {
      event.preventDefault();
      this.focusPreviousVisibleElement1(previousInputElement);
    }
  }
focusPreviousVisibleElement1(previousElement: HTMLElement): void {
    console.log('previousElement',previousElement)
    previousElement.focus()
  }


  focusNextVisibleElement1(nextElement: HTMLElement): void {
    console.log('nextInput',nextElement)
    nextElement.focus()
  }

//this is code from my component.html

<div class="mb-3">
          <label for="City" class="form-label">Add City</label>
          <select
            #selectValue
            formControlName="selectOption"
            (keydown)="onEnterKeyPress($event, city,mobileNoInput)"
            id="city"
          >
            <option value="Y">Y</option>
            <option value="N">N</option>
          </select>
        </div>

        <div class="mb-3" *ngIf="acceptCity()">
          <label for="city" class="form-label">City</label>
          <ng-select
            class="form-control"
            #city
            formControlName="city"
            [items]="cities"
          >
          </ng-select>
        </div>

#city is the element reference of city input but, this element only appears on page if acceptCity() is true , and until then i am not able to pass this city reference to onEnterKeyPress() method, I need to way to solve this error

1

There are 1 best solutions below

2
Yura Khomitskyi On

I see two options here:

  • Make the city reference the last optional argument in the method.
  • Use ViewChild and do not pass the #city reference to the method.