简体   繁体   English

Angular2将函数参数传递给构造函数

[英]Angular2 pass function argument to constructor

I'm trying to make some kind of @Component factory where I call a function that returns a component. 我正在尝试建立某种@Component工厂,在其中我调用一个返回组件的函数。 And I want to pass the widgetName to the constructor or to the super constructor. 我想将widgetName传递给构造函数或超级构造函数。 How do I pass an argument to a constructor? 如何将参数传递给构造函数?

export function createCommonKendoComponent(selector: string, **widgetName**: string) {
    @Component({
        selector: selector,
        inputs: ['bound', 'role'],
        bindings: [ElementRef]
    })

    @View({ template: '<ng-content></ng-content>' })

    class CommonComponent extends KendoComponent {
        constructor(elementRef) {
            super(elementRef, **widgeteName**);
        }
    }

    return CommonComponent;
}

You add it as provider somewhere. 您将其添加为提供程序。 Because a function doesn't have a type that can be used as provider you need to use a token. 由于函数没有可以用作提供程序的类型,因此需要使用令牌。 A token can be either a string or an OpaqueToken 令牌可以是字符串或OpaqueToken

var token = new OpaqueToken('myfunction');
bootstrap(AppComponent, [
    provide(token, 
        {useValue: (selector: string, **widgetName**: string) => { 
            createCommonKendoComponent(selector, **widgetName**}})]);
class CommonComponent extends KendoComponent {
    constructor(elementRef:ElementRef, @Inject(token) private compFactory) {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM