如何在angular2中实现页面滚动?

时间:2017-10-18 06:18:22

标签: angular angular2-routing

aboutData ['intro']包含以下html

<ul>
   <li><a href="#Om" target="_self">Om statistikk.siu.no</a></li>
   <li><a href="#Vilkar" target="_self">Vilkår for bruk</a></li>
</ul>
<p>  
  <a name="Om" id="Om"></a>
  Om statistikk.siu.no Lorem ipsum Lorem ipsum Lorem ipsum
</p>
<p>
  <a name="Vilkar" id="Vilkar"></a>
  Vilkar Lorem ipsum Lorem ipsum Lorem ipsum
</p>

单击href时,页面会滚动到相应的id元素,但它会显示错误:

Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'Vilkar'.

我无法在路由配置中定义这些href路由,因为这个html来自数据库并作为innerhtml附加到div元素。

<div [innerHTML]="aboutData['intro']|safeHtml"></div>

问题是我希望页面滚动但不会碰到路线。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

请尝试以下操作:我的示例代码

路由文件中的

重要{ path: '**', redirectTo: '', pathMatch: 'full' }如下所示

<强> home.route.ts

import { Routes } from "@angular/router";

import { HomeComponent } from './';

export const HomeRoute: Routes = [
    {
        path: '',
        component: HomeComponent
    },
    { path: '**', redirectTo: '', pathMatch: 'full' }
];

<强> home.module.ts

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

const HOME_STATES = [
    ...HomeRoute
];

@NgModule({
    imports: [
        RouterModule.forRoot(HOME_STATES, { useHash: true })
    ]
})

<强> home.component.html

<ul>
   <li><a href="#Om" target="_self">Om statistikk.siu.no</a></li>
   <li><a href="#Vilkar" target="_self">Vilkår for bruk</a></li>
</ul>
<p>  
  <a name="Om" id="Om"></a>
  Om statistikk.siu.no Lorem ipsum Lorem ipsum Lorem ipsum
</p>
<p>
  <a name="Vilkar" id="Vilkar"></a>
  Vilkar Lorem ipsum Lorem ipsum Lorem ipsum
</p>