通过将组件名称指定为输入参数将Angular组件导入另一个组件 在您的情况下您在问题中链接的堆栈闪电,您可以执行以下操作:

问题描述

我想创建一个由几个子组件组成的角度组件。最终,我想创建一个大型可重用的树组件,其节点具有不同的数据类型。对于每种数据类型,树组件将导入子组件,这些子组件指定应如何显示节点。用户应该能够指定一个自定义组件,以覆盖特定数据类型的认组件。这样的导入语法会很好:

<app-tree [customDateComp]="CustomDateComponent"></app-tree>

这可能是简化的tree.component.html:

<ng-container *ngIf="!customDateComp">
 <app-default-date></app-default-date>
</ng-container>
<ng-container *ngIf="customDateComp">
 {{ customDateComp }}
</ng-container>

当然这还行不通,因为这些组件是使用语法导入的。下面的方法也不起作用,因为angular可以将其转义:

<app-tree [customDateComp]="'<app-custom-date></app-custom-date>'"></app-tree>

示例代码可以在这里找到: https://stackblitz.com/edit/angular-ivy-xghj5f?file=src/app/app.component.html

有人知道如何通过将组件名称指定为输入参数来将Angular组件导入其他组件吗?还是有更好的方法来覆盖第三方组件的认子组件?非常感谢!

解决方法

您的stackblitz demo在这里工作。

在可能的方法中,有一个门户网站(以及@angular/cdk/portal中提供的实用程序)。

基本上,这就是您需要的:

1-所接收组件的占位符(在本例中为cdkPortalOutlet设置):

<ng-template [cdkPortalOutlet]="_compPortal"></ng-template>

2-一个可插入您的门户插座的门户(上面的_compPortal

_compPortal = new ComponentPortal<any>(MyCustomComponent);

仅此而已。

在您的情况下(您在问题中链接的堆栈闪电),您可以执行以下操作:

0-导入@angular/cdk/portal模块:

import {PortalModule} from '@angular/cdk/portal';

@NgModule({imports: [ ... PortalModule ] ...}) export class AppModule { }

1-tree.component.html

<ng-container *ngIf="!_compPortal">
 <app-date></app-date>
</ng-container>
<ng-container *ngIf="_compPortal">
  <ng-template [cdkPortalOutlet]="_compPortal"></ng-template>
</ng-container>

2-tree.compoenent.ts

@Input() 
set customDateComp(customComp: any){
  this._compPortal = customComp ? new ComponentPortal(customComp) : null;
}
_compPortal: ComponentPortal<any>;

3-app.component.ts

// Notice this is not `_comp: CustomDateComponent`.
// I'm setting up an attribute that receives the type so I can 
// make it available on the template
_comp = CustomDateComponent;

4-app.component.html

<app-tree [customDateComp]="_comp"></app-tree>
,

您可以使用动态组件加载程序https://angular.io/guide/dynamic-component-loader