【问题标题】:How can I route from a component to a section of another component in Angular?如何在 Angular 中从一个组件路由到另一个组件的一部分?
【发布时间】:2020-11-17 21:18:20
【问题描述】:

我有两个组件,它们位于不同的路径中。在第二个组件中有一个 div。我想从第一个组件路由到第二个组件的 div。是的,路由第二个组件很简单。但我想滚动到 div 的顶部。

感谢您的回答。

【问题讨论】:

    标签: html css angular routes


    【解决方案1】:

    这个标签在component1中声明

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

    这是组件2的变化

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

    你的component2 html会是这样的

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

    这里是更新和有效的 stackblitz https://angular-fragment-example.stackblitz.io

    【讨论】:

      【解决方案2】:

      我想你正在寻找Fragments

      官方文档:Angular Docs- Query Params and Fragments

      例子:

      手动导航

      c1.html

      &lt;a [routerLink] = "['/c2']" [fragment]="c2id"&gt; Link &lt;/a&gt;

      c2.html

      &lt;div id="c2id"&gt;content&lt;/div&gt;

      程序化导航

      c1.ts

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

      获取片段:

      c2.ts

      private fragment: string;
      constructor(private activatedRoute: ActivatedRoute){}
      
      ngOnInit(){
        this.fragment = this.activatedRoute.snapshot.fragment;
      }
      
      

      【讨论】:

      • 结果如何?
      • 滚动没有出现在div的顶部
      • 你能在 stackblitz 中复制你的结果吗?
      • 是的,我可以。 stackblits 中的 URL 如下:stackblitz.com/edit/angular-afdrkn
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多