gpt4 book ai didi

angular - 如何将组件类型传递给 Angular 中的另一个组件?

转载 作者:太空狗 更新时间:2023-10-29 18:16:00 26 4
gpt4 key购买 nike

我有一个基础组件 (MyBaseComponent) 从它的调用程序 (App) 接收数据。

我想知道我的基础组件是否有可能被它的调用者告知它应该使用什么“显示”组件——MyDisplayComponentMyOtherDisplayComponent

即,我想按照以下方式做一些事情:

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

同样,这里最大的“问题”是是否可以指定 displayapp.ts(调用程序)级别使用的组件,以便 my-base.component.ts 文件可以忽略在给定情况下使用的具体实现。

可能是 my-base.component.ts 文件需要传递一个类名或一个类型来使用,它遵循某种接口(interface)......?

在此先感谢您的帮助。

最佳答案

您可以使用 ngComponentOutlet 选择组件,可能还可以使用 ngIf 或切换要显示的组件,我不确定您要做什么。

Plunker

<ng-container *ngComponentOutlet="MyDisplayComponent"></ng-container>

// in module
entryComponents : [ MyDisplayComponent, MyOtherDisplayComponent],

关于angular - 如何将组件类型传递给 Angular 中的另一个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44314501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com