How can I route from a component to a section of another component in Angular?

Viewed 1364

I have two components and they are situtated in the different routes. In the Second component There is a div. I want to route from first component to the div of the second component. Yes, It is simple to route the second component. But I want to scroll be top of the div. enter image description here

Thank you for answers.

2 Answers

This tag is declared in component1

<a [routerLink] = "['/c2']" fragment="c2id"> Link </a>

Here are the component2 changes

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-c2',
  templateUrl: './c2.component.html',
  styleUrls: ['./c2.component.css']
})
export class C2Component implements OnInit {
  private fragment: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.fragment.subscribe(fragment => {
      this.fragment = fragment;
    });
  }
  ngAfterViewInit(): void {
    try {
      document.querySelector('#' + this.fragment).scrollIntoView();
    } catch (e) {}
  }
}

And your component2 html will be like this

<p style="height: 800px;">
c2 works!
</p>
<hr>
<div id="c2id" style="height: 500px;">
  The div with c2id
</div>

Here is the updated and working stackblitz https://angular-fragment-example.stackblitz.io

I think you are looking for Fragments.

Official Docs : Angular Docs- Query Params and Fragments

Examples:

Manual Navigation

in c1.html

<a [routerLink] = "['/c2']" [fragment]="c2id"> Link </a>

in c2.html

<div id="c2id">content</div>

Programatic Navigation

in c1.ts

private fragmentSetDynamically: string;
constructor(private router: Router){}

onClickButton(){
   this.router.navigate(['/c2'], {fragment: fragmentSetDynamically});
}

Getting the fragment :

in c2.ts

private fragment: string;
constructor(private activatedRoute: ActivatedRoute){}

ngOnInit(){
  this.fragment = this.activatedRoute.snapshot.fragment;
}

Related