简体   繁体   中英

Angular 2 routing to specific part of a webpage from one component link to another component

I have a link in footer that takes to the terms page but I want that link to take to a specific part of the terms webpage (3rd paragraph in terms).

Here is the code for footer.component.html

<a routerLink="terms">Terms & conditions</a> | 
<a routerLink="terms">Privacy policy</a> | 
<a routerLink="terms">Cancellation policy</a>

In terms.component.html is the place where i want the privacy policy link in the footer to be opened when clicked.

<ol start="3">
    <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
</ol>

What do we need to use for these to work? Any help is appreciated. Thanks.

Here is the answer ,

and <a routerLink="terms">Terms & conditions</a> | <a routerLink="terms">Privacy policy</a> | <a routerLink="terms">Cancellation policy</a> <a routerLink="terms">Terms & conditions</a> | <a routerLink="terms">Privacy policy</a> | <a routerLink="terms">Cancellation policy</a>

Instead of just using . <a routerLink="terms">Terms & conditions</a>

use like this

 <a [routerLink]="['/terms']" fragment="terms"> Terms & conditions </a>
 <a [routerLink]="['/terms']" fragment="cancel"> Cancellation policy </a>
 <a [routerLink]="['/terms']" fragment="privacy"> Privacy policy </a>

page should be like

<ol start="3" id="privacy" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
</ol>

 <ol start="3" id="terms" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
 </ol>

 <ol start="3" id="cancel" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
 </ol>

Refer to the API for detailed descriptions and usage. - https://angular.io/api/router/RouterLink

To add to @Rahul VV's answer i have edited component with event scrollIntoView below like this

footer.component.ts

import { Router, NavigationEnd } from '@angular/router';

constructor(router: Router) {
    router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(); }
        }
      }
    });
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM