[英]Angular 2 More than one component on same page
我正在使用app.component.ts文件中的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 { }
這不起作用......是我做錯了還是不允許這樣做?
在頁面中不能有兩個具有相同選擇器的根組件,也不能在同一個類上有兩個@Component()
裝飾器。
如果您的組件具有不同的選擇器,則只需為每個根組件運行bootstrap
@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
您不能擁有包含兩個組件裝飾器的組件(@Component)。 您需要為此創建兩個不同的類:
@Component({
selector: 'app',
template: `<h1>Title Here</h1>`
})
export class AppComponent { }
@Component({
selector: 'appTwo',
template: `<h1>Another Title Here</h1>`
})
export class AppComponent1 { }
然后你可以使用Gunter答案中的方法......
如果這對任何人都有幫助,可以用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頁面
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.