2017-04-03 97 views
1

任何人都可以请指导如何使用Smooth Scroll Polyfill与Angular 2 CLI使用Smooth Scroll Polyfill与Angular 2 CLI

我尝试添加下面polyfills.ts但它抛出错误的工作需要

require('smoothscroll-polyfill').polyfill(); 

我再尝试添加

import 'smoothscroll-polyfill'; 

虽然没有构建过程中引发任何错误,但当我在浏览器中运行该项目时,在控制台上显示以下错误:

ERROR TypeError: Failed to execute 'scroll' on 'Window': No function was found that matched the signature provided. 

回答

0

包括在assets文件夹中的smoothscroll.js,然后把它放在index.html

<script type="text/javascript" src="assets/smoothscroll.js"></script> 

作品与此:

ngOnInit(){ 

    window.scroll({ top: 200, left: 0, behavior: 'smooth' }); 
} 
+2

它被认为是更好的做法,把这个'scripts'在'.angular-cli.json',从'node_modules'加载它。 – 2017-04-03 02:53:06

+0

感谢您的回复,但由于在角度cli项目中有一个名为polyfills.ts的文件,我相信应该在此文件中添加polyfills。我遇到了这个http://stackoverflow.com/a/42982811/2755616但它似乎没有工作。 –

1

海尔角2/4的解决方案:

将这个两行在你的src/polifills.ts中:

import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll.js'; 

smoothscroll.polyfill();

+0

谢谢Stas,对我来说这是作品: 从'smoothscroll-polyfill'导入{polyfill}; polyfill(); –

4

您需要安装填充工具和@types

  1. yarn add smoothscroll-polyfillnpm install smoothscroll-polyfill
  2. yarn add @types/smoothscroll-polyfillnpm install @types/smoothscroll-polyfill

所以,在你的代码,你应该初始化的填充工具在组件或服务你想使用这个polyfill:

import * as smoothscroll from "smoothscroll-polyfill"; 

@Component({ 
    selector: 'app-my-demo', 
    templateUrl: './app-my-demo.html', 
    styleUrls: ['./app-my-demo.css'] 
}) 
export MyClass my implements OnInit { 

    constructor(
) { 
    smoothscroll.polyfill(); 
    } 

你可以在组件中使用,例如:

clickAnyThing(event:any){ 
    window.scroll({ top: 0, left: 0, behavior: 'smooth' }); 
    } 
1

如果您正在使用的角度CLI

首先安装软件包:

npm install smoothscroll-polyfill

然后添加以下在apps.scripts数组下的angular-cli.json:

"../node_modules/smoothscroll-polyfill/src/smoothscroll.js"

然后尝试类似:

window.scroll({ top: 400, left: 0, behavior: 'smooth' });

它应该工作。

2

这是怎么我在polyfills.ts文件中设置它:

import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll'; 
smoothscroll.polyfill(); 

然后你可以使用它像这样:

your_element.scrollIntoView({ behavior: 'smooth' }); 
+0

这也曾为我工作,但最近爆发了。现在我不得不在像@caballerog建议的组件中这样做。 – Methodician