Skip to content
Advertisement

Listen when a Dom element appears in Angular

I have a search bar icon 🔍 when you click it the search bar appears ▭

The code responsable for showning the search bar ▭ :

<ion-icon (click)="toggleSearchBar()" name="search"></ion-icon>

The Function:

toggleSearchBar() {
    this.shouldShowSearchBar = !this.shouldShowSearchBar;
    this.searchBarEl.setFocus();
}

But I have this problem:

1- I need to wrap this.searchBarEl.setFocus(); inside setTimeout because the search bar is wrapped inside *ngIf="shouldShowSearchBar" which is not rendered so fast so if I don’t wrap the method inside timeout it won’t call because the dom element would have not appeared.

Can I listen when a Dom element appears in Angular?

Advertisement

Answer

If you change *ngIf="shouldShowSearchBar" to [hidden]="!shouldShowSearchBar" then the DOM will already contain the HTML element and you will not have to add setTimeout to your event handling code toggleSearchBar. You could also use ngClass or ngStyle in the same manner with the css display: none.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement