[英]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.
在第二个组件中有一个 div。 I want to route from first component to the div of the second component.
我想从第一个组件路由到第二个组件的 div。 Yes, It is simple to route the second component.
是的,布线第二个组件很简单。 But I want to scroll be top of the div.
但我想滚动到 div 的顶部。
Thank you for answers.谢谢你的回答。
This tag is declared in component1该标记在 component1 中声明
<a [routerLink] = "['/c2']" fragment="c2id"> Link </a>
Here are the component2 changes这是 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) {}
}
}
And your component2 html will be like this而你的component2 html会是这样的
<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这是更新和工作的 stackblitz https://angular-fragment-example.stackblitz.io
I think you are looking for Fragments
.我认为您正在寻找
Fragments
。
Official Docs: Angular Docs- Query Params and Fragments官方文档: Angular Docs-Query Params and Fragments
Examples:例子:
Manual Navigation手动导航
in c1.html
在
c1.html
<a [routerLink] = "['/c2']" [fragment]="c2id"> Link </a>
in c2.html
在
c2.html
<div id="c2id">content</div>
Programatic Navigation程序化导航
in c1.ts
在
c1.ts
private fragmentSetDynamically: string;
constructor(private router: Router){}
onClickButton(){
this.router.navigate(['/c2'], {fragment: fragmentSetDynamically});
}
Getting the fragment:获取片段:
in c2.ts
在
c2.ts
private fragment: string;
constructor(private activatedRoute: ActivatedRoute){}
ngOnInit(){
this.fragment = this.activatedRoute.snapshot.fragment;
}
I have two components and they are situtated in the different routes.我有两个组件,它们位于不同的路线上。 In the Second component There is a div.
在第二个组件中有一个 div。 I want to route from first component to the div of the second component.
我想从第一个组件路由到第二个组件的 div。 Yes, It is simple to route the second component.
是的,路由第二个组件很简单。 But I want to scroll be top of the div.
但我想滚动到 div 的顶部。
Thank you for answers.谢谢你的回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.