在导航时,将URL的Fragment设置为你想要导航回的特定部分。例如:如果你想导航回ID为“section2”的部分,你可以使用以下代码:
router.navigate([], { fragment: 'section2' });
然后在你的组件中使用ViewChild指令来访问该部分。例如:
import { Component, ViewChild, ElementRef } from '@angular/core'; import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-my-component',
template:
})
export class MyComponent implements OnInit {
@ViewChild('section1') section1: ElementRef;
@ViewChild('section2') section2: ElementRef;
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() { this.route.fragment.subscribe(fragment => { if (fragment === 'section2') { this.scrollTo(this.section2); } }); }
private scrollTo(element: ElementRef) { element.nativeElement.scrollIntoView(); } }
如果你使用的是queryParams而不是Fragment进行导航,则可以将你想要导航回的特定部分转换为参数,并在导航时传递它。例如:
router.navigate([], { queryParams: { section: 'section2' } });
然后在你的组件中使用ActivatedRoute来获取该参数,并使用ViewChild指令访问该部分。例如:
import { Component, ViewChild, ElementRef } from '@angular/core'; import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-my-component',
template:
})
export class MyComponent implements OnInit {
@ViewChild('section1') section1: ElementRef;
@ViewChild('section2') section2: ElementRef;
constructor(private
上一篇:Angular:无法将一个子组件的输出传递给另一个子组件
下一篇:Angular:无法使用ExcelJS导出Excel - 错误TS2307:找不到模块'stream' - 错误TS2503:找不到命名空间'NodeJS'。