要在Angular 7中动态加载的HTML中导航到id为"article-1"的部分,可以使用Angular的内置Router模块来实现。
首先,确保已经安装了Angular的Router模块。可以使用以下命令安装:
npm install @angular/router
然后,在需要导航到id为"article-1"的HTML部分的组件中,添加以下代码:
import { Router, ActivatedRoute, NavigationExtras } from '@angular/router';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.route.fragment.subscribe(fragment => {
if (fragment) {
this.navigateToFragment(fragment);
}
});
}
navigateToFragment(fragment: string) {
const element = document.querySelector('#' + fragment);
if (element) {
element.scrollIntoView();
}
}
navigateToArticle() {
const navigationExtras: NavigationExtras = {
fragment: 'article-1'
};
this.router.navigate(['your-component-route'], navigationExtras);
}
}
在上面的代码中,navigateToFragment
函数用于导航到指定的id元素。navigateToArticle
函数用于在路由导航到该组件时触发导航到id为"article-1"的部分。
在模板中,可以添加一个按钮或其他触发导航的元素,并绑定到navigateToArticle
函数:
确保将"your-component-route"替换为你的组件的实际路由路径。
这样,当点击按钮或触发导航的元素时,Angular将会导航到具有id为"article-1"的部分,并滚动到该部分。