最佳答案
这个标签在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
关于html - 我如何从一个组件路由到 Angular 中另一个组件的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63134018/