【问题标题】:Angular2 pass function argument to constructorAngular2将函数参数传递给构造函数
【发布时间】:2016-03-11 09:12:33
【问题描述】:

我正在尝试创建某种@Component 工厂,在其中我调用一个返回组件的函数。我想将 widgetName 传递给构造函数或超级构造函数。如何将参数传递给构造函数?

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;
}

【问题讨论】:

    标签: javascript angular components factory


    【解决方案1】:

    您将它作为提供者添加到某处。因为函数没有可用作提供者的类型,所以您需要使用令牌。令牌可以是字符串或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) {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2015-10-11
      相关资源
      最近更新 更多