转到特定路线的div元素 [英] Go to particular Route's div element

查看:79
本文介绍了转到特定路线的div元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两条路线.从一条路线中,我需要通过单击按钮来获取另一条路线的div元素.我对id(#)的处理方式与我们在HTML中所做的类似,但无法解决.您能建议在Angular中做一个最好的方法吗?

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>

路线一(/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

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 ]
})

然后在您要滚动到的div上指定ID

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使用片段导航到当前div位置

Finall Use fragment to navigate to the current div location

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

示例: https://stackblitz.com/edit/angular-h7bvyu

这篇关于转到特定路线的div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆