htmlcssangularroutes

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


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.


Solution

  • 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