欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Angular 利用路由跳转到指定页面的指定位置方法

程序员文章站 2022-10-15 08:07:53
之前做过页面内的跳转,比较简单,最近项目需要实现跨页面跳转,并跳转到指定地点,试了很多方法,有用到传递参数然后让页面滚动相应的距离,但是一旦文章长短发生变化,滚动的距离也需...

之前做过页面内的跳转,比较简单,最近项目需要实现跨页面跳转,并跳转到指定地点,试了很多方法,有用到传递参数然后让页面滚动相应的距离,但是一旦文章长短发生变化,滚动的距离也需要重新计算,比较麻烦,所以最后总结出这两种比较靠谱的方法,只需要在需要跳转的地方加上合适的id就行,原理和单页面内跳转相似。

detail.component.html

<p>you'll see which payment methods are available to you on the checkout page, before you submit a reservation request. after you select your country, all of your payment details will be shown.</p>
<p id="readmore">we charge featured guide who offer journey a 15% service fee. the amount of the service fee is calculated from the price that featured guide set for their journey. you will see the service fee when you set your price before submitting a journey. the service fee is automatically deducted from the payout to the host.
  

depending on the laws of the jurisdiction involved, vat may be charged on top of the service fee. the service fee will include these vat charges when applicable.</p>

app.component.html

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

app.route.ts

 { path: '',component: logincomponent},
 { path: 'detail', component: detailcomponent },
 { path: '**',component: notfoundcomponent}

方法一:新增路由地址来实现

app.route.ts

 { path: '',component: logincomponent},
 { path: 'detail', component: detailcomponent },
 { path: 'detail#readmore',component: notfoundcomponent},
 { path: '**',component: notfoundcomponent}

app.component.ts

readmore() {
this.router.navigatebyurl('/detail#readmore');
 }

detail.component.ts

ngoninit() {
 if (window.location.hash === '#readmore') {
  window.location.assign('detail#readmore');
 }
 }

方法二:在原路由地址不变的情况下,利用路由传递参数来实现

app.component.ts

readmore() {
 this.router.navigate(['/detail', { id: 'readmore'}]);
 }
detail.component.ts

this.myactivatedroute.params.subscribe(
  (data: any) => {
  if (data.id === 'readmore') {
   window.location.assign('detail#readmore');
  }
  }
 );

以上这篇angular 利用路由跳转到指定页面的指定位置方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。