通过将零部件名称指定为输入参数,将"角度零部件"导入到另一个零部件中



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

<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>

当然,这还不起作用,因为组件是用语法导入的。下面的方法也不起作用,因为角度逃脱了它:

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

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

有人知道如何通过指定组件名称作为输入参数将角度组件导入到其他组件中吗?或者有更好的方法来覆盖第三方组件的默认子组件吗?非常感谢!

这是您的stackblitz演示。

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

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

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

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

2-插入您的门户出口的门户(_compPortal,如上(:

_compPortal = new ComponentPortal<any>(MyCustomComponent);

仅此而已。

在您的情况下(您在问题中链接的stackblitz(,您可以:

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-树组件.ts

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

3-应用程序组件.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-应用程序组件.html

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

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

最新更新