【问题标题】:How to implement scroll on page in angular2?如何在angular2中实现页面滚动?
【发布时间】:2017-10-18 06:18:21
【问题描述】:

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>

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

【问题讨论】:

  • 您可以添加匹配所有内容的通配符路由以避免此错误path: '**', ...
  • 这是我的页面网址:localhost:4200/#/…。如果我使用 {path:'**', redirectTo:'source', pathMatch:'full'} 。然后点击链接后它变成localhost:4200/#/source。单击链接后,我想像以前一样维护 url。
  • 我明白了。 href="#Om" 似乎与 HashLocationStrategy 冲突。您可以尝试使用默认值 (PathLocationStrategy) 吗?
  • 我的整个应用程序都是在 hashlocationstrategy 上开发的,如何迁移到路径定位策略
  • 如果整个应用程序都是 Angular,那么您只需要删除 LocationStrategy 提供程序或 useHash: true(取决于您启用它的方式)。您需要确保使用的服务器配置为支持PathLocationStrategy

标签: angular angular2-routing


【解决方案1】:

尝试如下:我的示例代码

在您的路由文件中添加重要的{ 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>

【讨论】:

  • 它没有用。如果我在 redirectTo 属性中使用空白,则 URl 变为 localhost:4200/#
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多