How to add a new instance of the same component in Angular2

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


Everything:

I'm new to angular2, when I follow the quick start guide, one question confuses me:

I simplify 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 add another my-app tag to index.html, for example:

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

I wonder why the second can not be displayed?

Another question related to this:

If I put two instances of the same component, each of them will save its own member variable, but if I add the service to one component, then all instances of the components will have the same service instance, I believe that the only obvious diff - they use different annotations (in addition, they both export the class): @Component and @Injectable, and one in the array of directives, and the other in the array of providers. I wonder if these 2 angular annotations tell how to handle an instance or array of directives and an array of providers?

+5
source share
3 answers

Angular2 does not allow you to load the same component twice on an HTML page.

However, you can probably download the various application components on the same HTML page, if you wish.

See this documentation for more details:

Edit

As for your second question, you should know that @Component and @Injectable are decorators. They are responsible for wrapping the target instances and allow dependency injection by providing the correct dependency instances in the constructor based on the configured metadata.

As for hierarchical injectors, you can look at this link:

+4
source

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

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

+2
source

As far as I know, in addition to the main component, you can use any other component several times on the same html page.

You can achieve this using @Input decorator. Declare an attribute to your selector element / directive in html and get the value of this attribute in Component using @Input decorator

import {Component, Input} from "angular2 / core";

 @Component({ selector: "my-app", template: "<div>{{title}}</div>" }) export class AppComponent { @Input() title; } <body> <my-app title = "somedata1">Loading...</my-app> <my-app title = "somedata2">Loading...</my-app> </body> 

You can find an example in this link.

Angular2 .. Using the same component to display different data on the same page depending on the response of the service

-1
source

Source: https://habr.com/ru/post/1244596/


All Articles