我正在尝试使用 Angular 2 和 TypeScript 创建一个工厂方法,但我显然没有以正确的方式进行操作,因为我的 TSC 编译器抛出了一个虚假错误:
error TS1005: ',' expected.
我正在尝试将类型作为 @Input()
传递给这样的组件:
<custom-user [componentType]="CreateMeComponent"></custom-user>
我有这个代码:
// custom-user.component.ts
export class GalleriaCustomUserComponent implements OnChanges {
@Input() componentType: any; // is there a type for types, other than any?
@ViewChild(ComponentDirective) componentAnchor: ComponentDirective;
ngAfterViewInit() {
this.componentAnchor
.createComponent<this.componentType>(); // this line throws the ',' error
}
}
指令看起来像这样:
// component.directive.ts
@Directive({
selector: '[componentAnchor]'
})
export class ComponentDirective {
constructor(
private viewContainer: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) {}
public createComponent<MyComponent>() {
this.viewContainer.clear();
let componentFactory =
this.componentFactoryResolver.resolveComponentFactory(MyComponent);
let componentRef = this.viewContainer.createComponent(componentFactory);
return componentRef;
}
}
这可能吗?或者这是一个糟糕的设计?
最佳答案
您不能在 View 绑定(bind)中使用类型名称。仅支持对组件实例或模板变量的引用。将类型分配给组件的属性,然后就可以使用它了:
<custom-user [componentType]="createMeComponent"></custom-user>
createMeComponent = CreateMeComponent;
关于angular - 将类型传递给组件并将该类型转发给工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39486517/