【发布时间】:2020-11-17 21:18:20
【问题描述】:
【问题讨论】:
【问题讨论】:
这个标签在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
【讨论】:
我想你正在寻找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;
}
【讨论】: