如何在Angular中实现跳转至不同组件的指定锚点区域
解决方案
1. 扩展app-button组件支持锚点参数
首先在app-button.component.ts中新增fragment输入属性:
import { Component, Input } from '@angular/core'; @Component({/* 原有组件配置 */}) export class AppButtonComponent { // 原有输入属性保留,新增以下内容 @Input() fragment?: string; }
修改app-button的模板代码,给routerLink绑定fragment属性:
<button [disabled]="disabled" type="submit" [replaceUrl]="replaceUrl" [skipLocationChange]="skipLocationChange" [routerLink]="url" [fragment]="fragment" class="btn" [ngClass]="{ 'btn-primary': !outline && bcgColor == 'green', 'btn-white text-primary': bcgColor == 'white', 'btn-outline': outline, disabled: disabled ? disabled : '' }" > <div> <span><ng-container *ngTemplateOutlet="passedValue"></ng-container></span><span></span> </div> </button>
2. 修改首页按钮调用配置
给按钮传入map作为锚点值:
<app-button [outline]="true" [url]="'/contact' | localize" fragment="map">{{ 'CONTACT.BTN' | translate}}</app-button>
3. 开启路由锚点滚动配置
在app-routing.module.ts中修改路由根配置,开启锚点滚动支持:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [/* 原有路由配置保留 */]; @NgModule({ imports: [RouterModule.forRoot(routes, { anchorScrolling: 'enabled', // 开启锚点自动滚动 scrollPositionRestoration: 'top' // 跳转后先回到页面顶部再滚动到锚点,避免历史滚动位置干扰 })], exports: [RouterModule] }) export class AppRoutingModule { }
4. (可选)异步内容兼容处理
如果你的google-map组件是异步加载的,会出现滚动时map元素还未渲染完成导致滚动失效的问题,在contact.component.ts中添加以下逻辑兼容:
import { Component, AfterViewInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ViewportScroller } from '@angular/common'; @Component({/* 原有组件配置 */}) export class ContactComponent implements AfterViewInit { constructor( private route: ActivatedRoute, private viewportScroller: ViewportScroller ) {} ngAfterViewInit(): void { this.route.fragment.subscribe(fragment => { if (fragment === 'map') { // 100ms延时确保地图元素渲染完成,也可以替换为google-map组件的加载完成事件触发回调 setTimeout(() => { this.viewportScroller.scrollToAnchor(fragment); }, 100); } }); } }
内容的提问来源于stack exchange,提问作者ashv9
相关产品推荐
相关产品推荐

