angular - 将类型传递给组件并将该类型转发给工厂

标签 angular typescript

我正在尝试使用 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/

相关文章:

angular - 如何选择组件模板中的元素?

android - 将方向更改为 'horizontal' 不会更改 RadListView 的滚动方向吗?

angular - 在 Angular 2 + Immutable.js 中迭代(使用 *ngFor)

javascript - 我们需要初始化一个数组吗?

angular - 重置 Angular 的 Mat 数据表搜索过滤器

typescript - Sequelize.js:Model.build 返回一个空白对象

angular - 使 mat-radio-button 成为表单中的必填字段

javascript - Microsoft 应用程序注册、身份验证和重定向 URL

javascript - 目前是否有将两个或多个字符串文字类型连接到 TypeScript 中的单个字符串文字类型的方法?

javascript - 可以使用枚举来限制值吗?