Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject new instance of same component in Angular2

Tags:

angular

[UPDATE] Please read the comment history to understand the context.


All:

I am pretty new to angular2, when I follow its quickstart guide, one question confuses me:

I simplify the app.component.ts as:

import { Component } from "angular2/core";
@Component({
    selector: "my-app",
    template: "<div>{{title}}</div>"
})
export class AppComponent {
        title = "Tour of Heroes" + Math.random();
}

And I add another my-app tag into index.html like:

  <body>
    <my-app>Loading...</my-app>
    <my-app>Loading...</my-app>
  </body>

I wonder why the second one can not get rendered?

Another question related to this is:

If I put two instance of same component, each one will keep their own member variable, but if I inject service into one component, then all component instances share the same service instance, I find the only obvious diff is they use different annotation( other than this, they both export a class): @Component and @Injectable, and one in directives array while the other in providers array. I wonder if these 2 annotation tell angular how can treat the instance or the directives array and providers array do that?

like image 716
Kuan Avatar asked Mar 07 '16 18:03

Kuan


2 Answers

Angular2 doesn't allow to bootstrap the same component twice in an HTML page.

This is however possible to bootstrap different application components if you want in a same HTML page.

See this documentation for more details:

  • https://angular.io/docs/ts/latest/api/platform/browser/bootstrap-function.html (Section "Bootstrapping Multiple Applications")

Edit

Regarding your second question, you need to be aware that @Component and @Injectable are decorators. They are responsible to "wrap" target instances and allow dependency injections by providing right dependency instances in constructor based on configured metadata.

Regarding hierarchical injectors, you could have a look at this link:

  • What's the best way to inject one service into another in angular 2 (Beta)?
like image 130
Thierry Templier Avatar answered Sep 28 '22 12:09

Thierry Templier


This is currently not supported. You need to initialize each root component with bootstrap(AppComponent) but that only works if both components have different selectors.

See also https://github.com/angular/angular/issues/7136

like image 22
Günter Zöchbauer Avatar answered Sep 28 '22 12:09

Günter Zöchbauer