Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...