2016-03-28 66 views
12

我正在使用app.component.ts文件中的Angular 2快速入門代碼。Angular 2在同一頁面上有多個組件

文件看起來是這樣的:

import {Component} from 'angular2/core'; 

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

可正常工作。

我想要做的就是添加此同一頁上的另一個組成部分...所以我嘗試這樣做:

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 { } 

這不工作...難道我做錯了什麼或者這是不允許的?

回答

19

在頁面中不能有兩個具有相同選擇器的根組件,在同一個類中也不能有兩個@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) 

有一個懸而未決的問題,以支持重寫選擇器可以添加一個根組件多次
- https://github.com/angular/angular/issues/915

+0

https://github.com/angular/angular/issues/915?重寫選擇器可能有哪些優點? – shiv

+0

您可以多次添加相同的根組件,但仍然不會出現在同一個選擇器上。 –

+0

我不知道是否有任何好處或理由有多個bootstrapped'root'組件......任何想法? @GünterZöchbauer –

3

您不能擁有帶有兩個組件裝飾器(@Component)的組件。您需要爲此創建兩個不同類別:

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

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

然後你可以使用的方法從岡特的答案...

-2

櫃面這是有幫助的人,可以做同樣的事情iframe出現。製備的樣品,你可以在這裏看到: http://plnkr.co/edit/xWKGS6

基本上我使用iframe的加載控件的HTML

<iframe src="widget.html" width="500" height="400" style="border:none; background-color:#ccc"> 
    </iframe> 

小部件是一個正常的angular2 HTML頁面

+2

儘管如此,使用共享服務與其他組件進行通信並不會那麼容易。 –

+1

是的,但是這個例子更多的是關於整個使用的相同組件,每個組件都是獨立的。所以就像一個小部件場景,比如說一個應用程序是否顯示網站中不同地點的不同城市。認爲這將是唯一的原因有人會想要加載它不止一個無論如何tbh :) – MSwehli

+0

使用iframe從來不是一個好主意,因爲缺乏控制 –

相關問題