我正在尝试在Angular 2中实现一个ComponentContainer,这样你就可以动态添加其他组件,类似于Android中的LinearLayout.
到目前为止,使用 Angular 2动态选项卡和用户单击选择的组件, 我可以动态添加传递Type的组件.
我的问题是使用这个方法,创建的Component只是由它的Type创建,我不知道如何给它提供参数.
这就是我所做的:
container.component.ts
import {
Component,
OnChanges,
AfterViewInit,
OnDestroy,
Input,
Type,
ViewChild,
ViewContainerRef,
ComponentRef,
ComponentResolver,
ComponentFactory
} from '@angular/core';
@Component({
selector: 'wrapper-component',
template: '<div #container></div>'
})
class WrapperComponent implements OnChanges, AfterViewInit, OnDestroy {
@Input() type: Type;
@ViewChild('container', {read: ViewContainerRef}) container;
cmpRef: ComponentRef<any>;
private isViewInitialized: boolean = false;
constructor(private resolver: ComponentResolver) { }
private updateComponent() {
if(!this.isViewInitialized)
return;
if(this.cmpRef)
this.cmpRef.destroy();
this.resolver.resolveComponent(this.type).then((factory: ComponentFactory<any>) => {
this.cmpRef = this.container.createComponent(factory);
})
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() { …Run Code Online (Sandbox Code Playgroud)