I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error:
error TS1005: ',' expected.
The issue arises when I try to pass a type as an @Input()
to a component in this manner:
<custom-user [componentType]="CreateMeComponent"></custom-user>
The relevant code snippet is as follows:
// custom-user.component.ts
export class GalleriaCustomUserComponent implements OnChanges {
@Input() componentType: any; // Can we specify a more specific type here?
@ViewChild(ComponentDirective) componentAnchor: ComponentDirective;
ngAfterViewInit() {
this.componentAnchor
.createComponent<this.componentType>(); // The error occurs in this line
}
}
Here is how the directive is implemented:
// 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;
}
}
Can this approach work, or does it indicate a flawed design?