首先,在目标组件中添加一个id为“myDiv”的div元素以便我们在其他组件中引用它。
This is my target div
接下来,在源组件中,我们需要导入Router和ActivatedRoute模块,并注入它们。
import { Router, ActivatedRoute } from '@angular/router';
...
constructor(private router: Router, private activatedRoute: ActivatedRoute) {}
然后,在按钮的点击事件处理函数中,我们可以通过以下方式导航到目标组件并滚动到目标div。
onButtonClick() {
this.router.navigate(['target-component'], {
queryParams: {
scrollTo: 'myDiv'
},
relativeTo: this.activatedRoute
});
}
在以上代码中,我们使用Router
的navigate
方法来导航到目标组件,我们可以通过queryParams
来传递滚动的目标点,这里我们将scrollTo
的值设置为“myDiv”。
同时,我们需要使用ActivatedRoute
来指定目标组件是相对于当前组件进行导航的。最后,我们需要在目标组件的ngAfterViewInit
中获取scrollTo
参数并将屏幕滚动到目标div。
ngAfterViewInit() {
this.activatedRoute.queryParams.subscribe(params => {
const element = document.getElementById(params.scrollTo);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
});
}
在这里,我们使用ActivatedRoute
模块中的queryParams
,以获取在导航命令中传递的scrollTo
参数值。我们使用document.getElementById()
方法找到目标div并使用scrollIntoView({ behavior: 'smooth' })
方法滚动到目标div。
当我们点击源组件中的按钮时,在导航到目标组件后,屏幕将自动滚动到id="myDiv"
的div元素。