- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个基础组件 (MyBaseComponent) 从它的调用程序 (App) 接收数据。
我想知道我的基础组件是否有可能被它的调用者告知它应该使用什么“显示”组件——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>
,但我不认为它提供了这种级别的灵 active 。另外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 {}
我的基础.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() {
}
}
my-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() {
}
}
同样,这里最大的“问题”是是否可以指定 display
在 app.ts(调用程序)级别使用的组件,以便 my-base.component.ts 文件可以忽略在给定情况下使用的具体实现。
可能是 my-base.component.ts 文件需要传递一个类名或一个类型来使用,它遵循某种接口(interface)......?
在此先感谢您的帮助。
最佳答案
您可以使用 ngComponentOutlet
选择组件,可能还可以使用 ngIf
或切换要显示的组件,我不确定您要做什么。
<ng-container *ngComponentOutlet="MyDisplayComponent"></ng-container>
// in module
entryComponents : [ MyDisplayComponent, MyOtherDisplayComponent],
关于angular - 如何将组件类型传递给 Angular 中的另一个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44314501/
我是一名优秀的程序员,十分优秀!