Navigate to a specific div in another component upon button click in Angular?

1.4k views Asked by At

I have a button on the top of a table. When user clicks that button, user should be able landed to the section 2 in the second page.

I tried as below but it's going only to that page, not landing to the section 2 div element Can someone explain how can I achieve this?

.firstPage.ts

addLease(){
    this.router.navigateByUrl('/secondPage/' + this.id);
  }

.firstPage.html

<button class="btn btn-primary btn-sm  ms-2" (click)="addLease()">  Lease Comp </button>

secondPage.html

<div #container>
  ............
  <div id="section1">
    .......
  </div>

  <div id="section2">
    ....
  </div>

</div>
1

There are 1 answers

0
erzen On

You can add your div id as query params

addLease(){
  this.router.navigate(
    ['/secondPage/' + this.id],
    { queryParams: { destination: 'yourDivId' } }
  );
}

And get it in your second component and use it to scroll to that div

 ngOnInit() {
    this.route.queryParams
      .subscribe(params => {
        document.getElementById(params.destination).scrollIntoView()
      }
    );
  }

You need to make checks for example as to not use IDs that are not in your HTML...