Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 More than one component on same page

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?

like image 884
Satch3000 Avatar asked Mar 28 '16 13:03

Satch3000


People also ask

Can you have multiple components in Angular?

Configuring Multiple ComponentsIn order to use our new components we need to add them to the declarations on our NgModule . And since we've changed our top-level component we need to set that in the bootstrap property as well as change our index. html to use the <app></app> root component instead.

What is nested components in Angular?

What are Angular Nested Components? The Angular framework allows us to use a component within another component and when we do so then it is called Angular Nested Components. The outside component is called the parent component and the inner component is called the child component.

Can a component have multiple templates?

Note Although it's possible for a component to render multiple templates, we recommend using an if:true|false directive to render nested templates conditionally instead. Create multiple HTML files in the component bundle.


1 Answers

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

like image 60
Günter Zöchbauer Avatar answered Oct 06 '22 07:10

Günter Zöchbauer