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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With