Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go to particular Route's div element

I have two routes. From one route I need to get another route's div element by button click. I done a similar way with id(#) that we do in HTML but It's not working out. Can you suggest a best way to do in Angular>

Route One (/route1)

<div class="div1">
<p>hi</p>
</div>

<div class="div2">
<p>hello</p>
</div>

Route two (/route2)

<button (click)="getDiv()"></button>

TS

getDiv()
{
      this.router.navigate(['/route1']); // I need to get div1 of route1 here
}
like image 372
Felix Christo Avatar asked Oct 19 '25 06:10

Felix Christo


1 Answers

If you are using angular 6.1+ version you can enable anchorScrolling manually

app.module.ts

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule.forRoot(route,{
       anchorScrolling: 'enabled'
  }) ],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent ]
})

Then specifies the id on the div which you want to scroll to

router-a.component.ts

<div class="div1"  id="div1">
<p>Div1</p>
</div>

<div class="div2" id="div2" >
<p>Div2</p>
</div>

Finall Use fragment to navigate to the current div location

getDiv() {
    this.router.navigate(['/route2'], { fragment: 'div2' });
  }

Example:https://stackblitz.com/edit/angular-h7bvyu

like image 138
Chellappan வ Avatar answered Oct 20 '25 19:10

Chellappan வ