Angular碎片导航无法工作。
创始人
2024-10-29 16:30:47
0
  1. 在app.module.ts文件中导入RouterModule,并在imports数组中添加RouterModule.forRoot([])。

import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [ // 定义路由 ];

@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

  1. 在HTML模板中,使用RouterLink指令将链接绑定到片段标识符。

Link to Section 1

  1. 在组件中,可以使用ActivatedRoute服务来获取当前路由的片段标识符。

import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router';

@Component({ selector: 'app-section', templateUrl: './section.component.html', styleUrls: ['./section.component.css'] }) export class SectionComponent implements OnInit { fragment: string;

constructor(private route: ActivatedRoute) { }

ngOnInit() { this.route.fragment.subscribe(fragment => { this.fragment = fragment; }); } }

  1. 如果要在初始化时滚动到片段,则可以使用ViewChild和ElementRef获取DOM元素,并使用scrollIntoView方法滚动到该元素。

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { ActivatedRoute } from '@angular/router';

@Component({ selector: 'app-section', templateUrl: './section.component.html', styleUrls: ['./section.component.css'] }) export class SectionComponent implements OnInit { @ViewChild('section1') section1: ElementRef;

constructor(private route: ActivatedRoute) { }

ngOnInit() { this.route.fragment.subscribe(fragment => { if (fragment === 'section1') { this.section1.nativeElement.scrollIntoView(); } }); } }

注意:片段标识符需要在路由定义中定义为一个参数。例如:

const routes: Routes = [ { path: 'page', component: PageComponent }, { path: 'page/:fragment', component: PageComponent } ];

相关内容

热门资讯

必备辅助推荐!麻友圈安庆版插件... 必备辅助推荐!麻友圈安庆版插件(透视)wepoker免费透视脚本(技巧教程有挂总结)这是一款可以让一...
总算了解!潮友辅助开挂(透视)... 大家好,今天小编来为大家解答wepoker辅助器软件下载这个问题咨询软件客服可以免费测试直接加微信(...
盘点一款!优乐江西辅助器(透视... 大家好,今天小编来为大家解答hhpoker辅助器视频这个问题咨询软件客服可以免费测试直接加微信(13...
透视有挂!小程序广东雀神智能挂... 透视有挂!小程序广东雀神智能挂件(透视)aapoker辅助插件工具(我来教教你有挂秘籍) 【无需打开...
一分钟快速了解!来玩app辅助... 一分钟快速了解!来玩app辅助器(透视)wpk俱乐部辅助器(黑科技教程有挂透视)【无需打开直接搜索加...
透视存在!老友内蒙麻将有挂吗(... 透视存在!老友内蒙麻将有挂吗(透视)德普之星透视辅助插件(wpk教程有挂技术)您好:德普之星透视辅助...
透视好友房!一键装方片十三张辅... 透视好友房!一键装方片十三张辅助(透视)hhpoker软件可以玩吗(微扑克教程有挂解惑);无需打开直...
重大通报!衢州都莱软件辅助器(... 您好:衢州都莱软件辅助器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
重大推荐!蜀山四川智能辅助插件... 您好:这款蜀山四川智能辅助插件下载游戏是可以开挂的,确实是有挂的,很多玩家在这款蜀山四川智能辅助插件...
透视中牌率!朋朋政和软件辅助器... 透视中牌率!朋朋政和软件辅助器(透视)aapoker辅助软件合法吗(新2026版真实有挂)《详细加薇...