【问题标题】:Dynamic Child Component in AngularAngular 中的动态子组件
【发布时间】:2020-01-05 10:24:44
【问题描述】:

我正在为元素列表构建一个具有一致设计模式的应用。如果我有一个 A 类型的对象,我将创建 AComponent,它接受 a 作为输入,然后创建另一个组件来遍历 A 的列表 AListComponent。然后,如果我有一个对象 B,我需要做同样的事情。似乎我应该能够在我想要迭代的对象的类中创建一个ObjectListComponent,以保持我的代码干燥。

例如,给定

组件控制器

...

@Input
a: A;
...

组件 HTML

<div>{{ a.name }}</div>

AListComponent 控制器

...

@Input()
aList: A[];
...

AListComponent HTML

<div *ngFor='let aObj of aList'>
    <app-a [a]='aObj'></app-a>
</div>

我们如何将AListComponent 抽象为ObjectListComponent

ObjectListComponent 控制器

...

@Input()
type: any;

@Input()
objects: <type>[]

objectComponent: any;

ngOnInit () {
  this.objectComponent = <get object component from type>
}

ObjectListComponent HTML

<div *ngFor='let obj of objects'>
    <app-objectComponent [object]='obj'></app-objectComponent>
</div>

ObjectListComponent 将被用作

...

<app-object-list [type]='A' objects='aList'></app-object-list>
...

【问题讨论】:

  • 您需要提供更多信息。 AComponentBComponent 有多少差异?我的意思是,它们都相似吗(css,函数)? this.objectComponent 的用途是什么,你打算如何使用它?如果唯一的区别是type,则创建接口ICanvasComponentInput,并在其中定义类型为obj: A | B。在 ObjectListComponent @Input 参数中使用它。 (尝试为 ObjectListComponent 提供更通用的名称)
  • 这个想法是ObjectListComponent 应该能够迭代任意模型列表,因为表示模型的组件是通过type 属性传入的。 this.objectComponent 将是表示通过 objects 属性传入的对象列表中的对象类型的组件。
  • 我想我得到了一点问题。如果您可以在 stackblitz.com 上创建一个演示,这对我真的很有帮助。我会从那里拿走它
  • 表示找不到请求的页面
  • 对不起,我之前没用过StackBlitz,所以还是习惯了。这应该工作:stackblitz.com/github/bicarlsen/temp

标签: javascript html angular typescript


【解决方案1】:

感谢您提供演示代码,Take a look at this demo code

主要逻辑在object-list.components.ts

ngAfterViewInit(){
     const component_obj = this.getComponentType(this.objects[0]);
      this.containers.map(
      (vcr: ViewContainerRef, index: number) => {
        const factory = this.resolver.resolveComponentFactory(
          component_obj);
        const componentRef = vcr.createComponent(factory);
        componentRef.instance['data'] = this.objects[index];
        this.cd.detectChanges()
      }
    )
 }

基本上,我所做的是:

  1. a.component.html:处理对象interface A

  2. 的逻辑
  3. b.component.html:处理interface B类型对象的逻辑

  4. 您可以在 home.component.html

  5. 中切换 2 种对象类型

显示组件 A

<app-object-list [objects]='aList'></app-object-list>

显示组件 B

<app-object-list [objects]='bList'></app-object-list>

您可以改进逻辑来检查和确定类型。那部分代码可以改进

【讨论】:

  • 我注意到发生了一个小错误,即列表中的一个元素没有出现。
猜你喜欢
  • 1970-01-01
  • 2019-05-14
  • 2017-02-24
  • 2023-03-14
  • 2019-02-06
  • 1970-01-01
相关资源
最近更新 更多