Home > Net >  Angular - how do I know which operation has called ngAfterViewChecked()?
Angular - how do I know which operation has called ngAfterViewChecked()?

Time:05-15

Consider a table, the rows of which are built dynamically - i.e. the HTML element contains an *ngIf directive.

On different occassions I want to scroll a selected table row into view. And because these are different occassions and I need the table to be fully built in order for this to work, I am performing this scroll into view operation inside ngAfterViewChecked().

So far, this has worked fine. Now, I have added a document.click listener on a different component, not the table, but a component that is on the same page as the table:

  @HostListener('document:click')
  documentClick(): void {
    // do something
  }

And this seems to be messing with my scrolling into view: When clicking a button, for example, which usually scrolls a selected table into view, ngAfterViewChecked() is executed twice, the second time, however, the wrong if-block inside this function is executed.

I wonder, if I could somehow check if ngAfterViewChecked() was called by the document.click event, so that I could handle this event inside an additional if-block?

I am also open to other suggestions.

CodePudding user response:

If you want to scroll to a table row when the page init you could do the scrolling in the AfterViewInit lifecycle hook.

The ngAfterViewChecked() is called with every change detection due to lifecycle hooks chain.

Check here.

In addition, you could perform the scroll listening to the click or other event that selects a table row.

  • Related