Suppose I\'ve got two separate components
. One defines the my-app
element, one defines the child
element.
I want the chi
In fact, it's something similar to what we have in the Typescript version ;-). You need to configure providers:
bootstrap
methodproviders
propertyThere are two great blog posts that can help you when writing Angular2 applications with ES5:
Here is a complete working sample with ES5 only:
index.html for JavaScript files to include
</cmp>
Definition of the service
var Service = function() {};
Service.prototype.greeting = function() {
return 'hello';
};
Definition of the component
var Cmp =
ng.core.Component({
selector: 'cmp'
}).
View({
template: '{{greeting}} world!'
}).
Class({
constructor: [Service, function(service) {
this.greeting = service.greeting();
}]
});
Bootstrap the Cmp
component as application component
document.addEventListener('DOMContentLoaded', function() {
ng.platform.browser.bootstrap(Cmp);
});
Dependency injection at application level. Simply add a second parameter to the bootstrap
function. Its value corresponds to an array containing the Service
object.
document.addEventListener('DOMContentLoaded', function() {
ng.platform.browser.bootstrap(Cmp, [Service]);
});
Dependency injection at component level. Simply add a providers
property in the component configuration object. Its value is an array containing the Service
object.
var Cmp = ng.core.
Component({
selector: 'cmp',
providers: [Service]
}).
View({
template: '{{greeting}} world!'
}).
Class({
constructor: [Service, function(service) {
this.greeting = service.greeting();
}]
});
If you want to use a component inside another one, simply leverage the directives
attribute of the view, as described below. The CmpChild
component is used within the Cmp
one.
var CmpChild = ng.core.
Component({
selector: 'child'
}).
View({
template: '{{greeting}} world!'
}).
Class({
constructor: [Service, function(service) {
this.greeting = service.greeting();
}]
});
var Cmp = ng.core.
Component({
selector: 'cmp'
}).
View({
template: ' ',
directives: [CmpChild]
}).
Class({
constructor: [Service, function(service) {
}]
});
Hope it helps you, Thierry