我有一個從它的調用者(App)接收數據的基本組件(MyBaseComponent)。如何將組件類型傳遞給Angular中的另一個組件?
我想知道是否有可能爲我的基本組件由它的調用什麼「顯示」部分應使用被告知 - MyDisplayComponent或MyOtherDisplayComponent。
也就是說,我想做的事的東西線:
<my-base [data]="names">
<my-other-display></my-other-display>
</my-base>
,並在不同的位置,喜歡的東西:
<my-base [data]="names">
<my-display></my-display>
</my-base>
但我無法弄清楚如何做這個。我嘗試了不同的使用<ng-content>
,但我不認爲它提供了這種靈活性水平。另外ComponentFactoryResolver
聽起來像它可以工作,但我不知道它如何以迭代的方式工作,以及將數據傳遞給子控件。
Here's a working Plunker,下面列出的代碼,希望傳達我試圖。
app.ts
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {MyBaseComponent} from './my-base.component'
import {MyDisplayComponent} from './my-display.component'
import {MyOtherDisplayComponent} from './my-other-display.component'
@Component({
selector: 'my-app',
template: `
<div>
<my-base [data]="names">
<!-- Is it possible to specify the 'display component' type to use here? -->
</my-base>
</div>
`,
})
export class App {
names: string[] = ["bill", "bob", "ben"];
constructor() {
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, MyBaseComponent, MyDisplayComponent, MyOtherDisplayComponent ],
bootstrap: [ App ]
})
export class AppModule {}
我-base.component.ts
import {Component, Input} from '@angular/core'
@Component({
selector: 'my-base',
template: `
<div *ngFor="let datum of data">
<!-- Instead of specifying the display components here,
how can I specify the components type to use for display
at the 'app.ts' level? -->
<!--<my-display [value]="datum"></my-display>-->
<my-other-display [value]="datum"></my-other-display>
</div>
`,
})
export class MyBaseComponent {
@Input()
data: string[];
constructor() {
}
}
我-display.component.ts
import {Component, Input} from '@angular/core'
@Component({
selector: 'my-display',
template: `
<div>{{value}}</div>
`,
})
export class MyDisplayComponent {
@Input()
value:string;
constructor() {
}
}
我-其他-display.component.ts
//our root app component
import {Component, Input} from '@angular/core'
@Component({
selector: 'my-other-display',
template: `
<div>{{value}}! {{value}}! {{value}}!</div>
`,
})
export class MyOtherDisplayComponent {
@Input()
value:string;
constructor() {
}
}
再次,大「問」這裏是它是否有可能在app.ts(調用)水平,使指定使用display
組件my-base.component.ts文件可能無法瞭解特定情況下使用的特定實現。
這可能是my-base.component.ts文件需要傳遞一個類名或一個類型來使用它,以符合某種接口...?
在此先感謝您的幫助。
這是非常好的 - 正是我所期待的。非常感謝! – Cuga