转到特定路线的 div 元素

2023-12-03

我有两条路线。从一条路线我需要通过单击按钮获取另一条路线的 div 元素。我做了类似的方式id(#)我们在 HTML 中这样做,但它不起作用。你能建议一个在 Angular 中做的最好的方法吗?

一号公路 (/route1)

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

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

路线二 (/route2)

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

TS

getDiv()
{
      this.router.navigate(['/route1']); // I need to get div1 of route1 here
}

如果您使用的是 Angular 6.1+ 版本,您可以手动启用anchorScrolling

应用程序模块.ts

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

然后指定要滚动到的div上的id

路由器-a.component.ts

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

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

Final 使用fragment导航到当前div位置

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

转到特定路线的 div 元素 的相关文章

随机推荐