如何在 Angular 2 Javascript 中使用ViewChild ?我已经参考了 angular.io文档,并且尝试了以下代码,但它不起作用。谁能帮我?提前致谢。
main.html
<router-outlet></router-outlet>
app.component.js
(function (app) {
app.AppComponent = ng.core
.Component({
selector: 'my-app',
templateUrl: 'app/views/main.html',
directives: [ng.router.ROUTER_DIRECTIVES], //<----not loading components here
viewProviders: [ng.http.HTTP_PROVIDERS],
queries: {
'viewChild1Component': new ng.core.ViewChild(app.Child1Component) //Parent calls Child 1 using ViewChild
},
})
.Class({
constructor: [ng.router.Router, ng.http.Http, function (router, http) {
this.router = router;
this.http = http;
}],
ngAfterViewInit: function () {
this.viewChild1Component.onSubmit();
},
});
ng.router
.RouteConfig([
//loading components here
{ path: '/child1', component: app.Child1Component, name: 'Child 1', useAsDefault: true },
])(app.AppComponent);
})(window.app || (window.app = {}));
child1.js
(function (app) {
app.Child1Component = ng.core
.Component({
selector: 'test',
template: '<div>Test</div>',
})
.Class({
constructor: [ng.router.Router, function (router) {
this.router = router;
}],
onSubmit: function () {
alert('Call from Parent');
},
});
})(window.app || (window.app = {}));
索引.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- 1. Load libraries -->
<script src="scripts/traceur-runtime.js"></script>
<script src="scripts/system.js"></script>
<!-- IE required polyfill -->
<script src="scripts/es6-shim.min.js"></script>
<script src="scripts/angular2-polyfills.js"></script>
<script src="scripts/Rx.umd.js"></script>
<script src="scripts/angular2-all.umd.js"></script>
<!--components-->
<script src="app/components/child1.js"></script>
<script src="app/components/child2.js"></script>
<!-- 2. Load our 'modules' -->
<script src='app/app.component.js'></script>
<script src='app/boot.js'></script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>