簡體   English   中英

如何從一個組件路由到 Angular 中另一個組件的一部分?

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

我有兩個組件,它們位於不同的路線中。 在第二個組件中有一個 div。 我想從第一個組件路由到第二個組件的 div。 是的,布線第二個組件很簡單。 但我想滾動到 div 的頂部。 在此處輸入圖像描述

謝謝你的回答。

該標記在 component1 中聲明

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

這是 component2 的變化

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

我認為您正在尋找Fragments

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

例子:

手動導航

c1.html

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

c2.html

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

程序化導航

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。 我想從第一個組件路由到第二個組件的 div。 是的,路由第二個組件很簡單。 但我想滾動到 div 的頂部。 在此處輸入圖像描述

謝謝你的回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM