Go to particular Route's div element

2019-08-29 08:43发布

问题:

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
}

回答1:

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



回答2:

your html should be in a different module and routing should be configured. Using the following code in the html would don the same routing.

<button [routerLink]="['/route1']">View All</button>

your router should be configured with the root.