我的目标是编写一个按钮,在点击时将用户带到网页的顶部。我将此逻辑直接应用于按钮角度组件文件,然后通过将其嵌套在主要组件下将其包含到网页中。我认为当我接线逻辑时有一个时间问题。我已经包含了所有相关的代码片段,如果还有其他我可以提供的内容,以便更好地帮助用户回答这个问题,请告诉我。
HACK:我发现将角度分量逻辑包装在System.import承诺中会引入正确的时序来连接按钮逻辑。不知道为什么:/。注意" Button组件TypeScript"中的注释代码。作为一个例子。
index.html中的HTML片段,其中定义了主要组件
<!-- 1. Load libraries -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script>
System.config({
packages: {
src: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import("src/development/app/main-component.js")
.then(null, console.error.bind(console));
</script>
</head>
<body>
<!-- main component -->
<main>Loading...</main>
<!-- end main component -->
<!-- javascript -->
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="src/development/js/main.js"></script>
<!-- end javascript -->
</body>
</html>
主要组件TypeScript
import {bootstrap} from "angular2/platform/browser";
import {Component} from "angular2/core";
import {FloatingActionButtonComponent} from "./shared/floating-action-button/floating-action-button-component";
/**
* Configuration for the main Angular Component
* @Component
* @attribute {directives} defines a list of components, allowing angular to properly identify the component selector
*/
@Component({
directives: [
FloatingActionButtonComponent
],
selector: "main",
templateUrl: "./src/development/app/main-view.html"
})
export class MainComponent { }
bootstrap(MainComponent);
主要组件视图HMTL
<div id="main-container">
<!-- floating action button -->
<floating-action-button></floating-action-button>
<!-- end floating action button -->
</div>
按钮组件TypeScript
import {Component} from "angular2/core";
@Component({
selector: "floating-action-button",
templateUrl: "./src/development/app/shared/floating-action-button/floating-action-button-view.html"
})
export class FloatingActionButtonComponent {
constructor() {
//System.import("path/to/a/directory/file.js").then(() => {
if (document.getElementById("to-top-button") !== null) {
document.getElementById("to-top-button").addEventListener("click", () => {
window.scrollTo(0, 0);
console.log("click");
});
}
//});
}
}
按钮组件HTML
<div class="to-top-button">
<button id="to-top-button"><span class="glyphicon glyphicon-chevron-up" aria-hidden="true"></span>
<br>Top
</button>
</div>
答案 0 :(得分:1)
如果您认为这是一个时间问题,请将呼叫包裹在setTimeout
:
setTimeout(() => window.scrollTo(0, 0), 1);
如果这不起作用,请包装整个构造函数内容。