2017-04-03 99 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