假设我有一个接口(或实际组件)ListItemRenderer和一个实现该接口的组件MyRendererComponent(或扩展基本组件)
@Component({ selector: 'my-renderer',template: '<div>My renderer</div>' }) export class MyRendererComponent implements ListItemRenderer { ... }
我想将这个具体的实现传递给另一个组件,例如
@Component({ selector: 'my-list',template: ` <ul [renderer]="renderer" [items]="items"> <li *ngFor="let item of items"> <!-- what goes here? --> </li> </ul> ` }) export class MyList { @Input() renderer: ListItemRenderer; @Input() items: any[]; ... }
显然,父组件将具有ListItemRenderer类型的公共属性渲染器.问题是,如何在我的< li>中使用该组件? (见上文“这里有什么?”)?
要使用* ngFor动态添加组件,你需要类似于
https://stackoverflow.com/a/36325468/217408中解释的dcl-wrapper(不推荐使用DynamicComponentLoader支持ViewContainerRef.createComponent(),但我没有尝试为包装器组件引入另一个名称.)
@Component({ selector: '[dcl-wrapper]',// changed selector in order to be used with `<li>` template: `<div #target></div>` }) export class DclWrapper { @ViewChild('target',{read: ViewContainerRef}) target; @Input() type; cmpRef:ComponentRef; private isViewInitialized:boolean = false; constructor(private resolver: ComponentResolver) {} updateComponent() { if(!this.isViewInitialized) { return; } if(this.cmpRef) { this.cmpRef.destroy(); } this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => { this.cmpRef = this.target.createComponent(factory) }); } ngOnChanges() { this.updateComponent(); } ngAfterViewInit() { this.isViewInitialized = true; this.updateComponent(); } ngOnDestroy() { if(this.cmpRef) { this.cmpRef.destroy(); } } }
并使用它
@Component({ selector: 'my-list',template: ` <ul [items]="items"> <li *ngFor="let item of items" dcl-wrapper [type]="renderer" ></li> </ul> ` }) export class MyList { @Input() renderer: ListItemRenderer; @Input() items: any[]; ... }