15

I am working from the Angular 2 quick start code on app.component.ts file.

The file looks like this:

import {Component} from 'angular2/core';

@Component({
    selector: 'app',
    template: `<h1>Title Here</h1>'
})
export class AppComponent { }

This works as expected.

What I want to do is to add another component on this same page ... so I tried this:

import {Component} from 'angular2/core';
import {ComponentTwo} from 'angular2/core';

@Component({
    selector: 'app',
    template: `<h1>Title Here</h1>'
}),

@Component({
    selector: 'appTwo',
    template: `<h1>Another Title Here</h1>'
})
export class AppComponent { }

This doesn't work...Is it that I'm doing something wrong or is this not allowed?

2 Answers 2

20

You can't have two root components with the same selector in your page, you also can't have two @Component() decorators on the same class.

If your components have different selectors, just run bootstrap for each root component

@Component({
    selector: 'app',
    template: '<h1>AppComponent1</h1>'
})
export class AppComponent1 { }

@Component({
    selector: 'appTwo',
    template: '<h1>AppComponent2</h1>'
})
export class AppComponent2 { }


bootstrap(AppComponent1)
bootstrap(AppComponent2)

There is an open issue to support overriding the selector to be able to add a root component multiple times
- https://github.com/angular/angular/issues/915

Sign up to request clarification or add additional context in comments.

8 Comments

github.com/angular/angular/issues/915 ? What could be the possible advantages of overriding selectors?
That you can add the same root component multiple times, still not to the same selector though.
I wonder if there's any benefit or reason to have multiple bootstrapped root components ... any idea? @GünterZöchbauer
Just a rookie question: How does AppComponent1 (or AppComponent2) know which @Component to target?
i have a query, please clarify, How a component knows which export class it should take? what is the relation between first component({selector: 'app'}) and export class AppComponent1 { } ?
|
3

You can't have a component with two component decorators (@Component). You need to create two different classes for this:

@Component({
    selector: 'app',
    template: `<h1>Title Here</h1>`
})
export class AppComponent { }

@Component({
    selector: 'appTwo',
    template: `<h1>Another Title Here</h1>`
})
export class AppComponent1 { }

Then you can use the approach from the Gunter's answer...

1 Comment

i have a query, please clarify, How a component knows which export class it should take? what is the relation between first component({selector: 'app'}) and export class AppComponent { } ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.