2016-11-15 46 views
0

我正在使用动态组件创建(resolveComponentFactory) ,因此它在静态@Input()属性下工作良好。但对于动态设置器而言,它不起作用。我不能这样做this.componentReference.instance[myPropVar]= someValue 与创建内部组件的setter。动态组件属性的设置器Angular 2

这可能吗?谢谢!在我的动态组件

的属性设置为:

@Input() set lockMessage(val: any) { 
    if (val) { 
     console.log("Visit details -> ", val); 

    } 
    } 

这就像在该职位 Angular 2 dynamic component creation

相同的,但我想添加一些财产有二传手我的动态创建的组件。

P.S.是。我试图设置我的财产动态组件与该建设

/** 
    * public updateSingleComponentProp -> update single prop on component instance 
    * @param prop {string} -> property name 
    * @param val {any} -> property value 
    * @returns {void} 
    */ 
    public updateSingleComponentProp(prop: string, val: any): void { 
     let compInstance = this.componentReference.instance; 

     compInstance[prop] = val; 

     if (compInstance.hasOwnProperty(prop) || compInstance.hasOwnProperty('_' + prop)) 
      compInstance[prop] = val; 
     else 
      throw new Error("Component doesn't have this property -> " + prop); 

    } 

并且它抛出一个错误,因为该属性不存在。我检查了组件实例并且该设置器存在于原型中

+2

你能给出[MCVE]演示你想要做什么? – jonrsharpe

+1

我不明白为什么这会是一个问题。 'myPropVar'是一个匹配属性名称的字符串('lockMessage'),对吧?如果只是必须访问它,则不需要'@Input()'。你有错误信息吗? –

+0

是的,我更新了我的帖子 – Velidan

回答

0

您得到undefined的原因是您的动态组件没有名为lockMessage的“自己”属性。该属性(setter)属于DynamicComponent.prototype

让我们来看看打字稿如何编译下面的代码:

export class MyDynamicComponent { 
    text: string; 

    set lockMessage(val: any) { 
    if (val) { 
     console.log("Visit details -> ", val); 
    } 
    } 
} 

输出将是如下:

function MyDynamicComponent() {} 

Object.defineProperty(MyDynamicComponent.prototype, "lockMessage", { 
    set: function (val) { 
     if (val) { 
      console.log("Visit details -> ", val); 
     } 
    }, 
    enumerable: true, 
    configurable: true 
}); 

您也可以使用getOwnPropertyDescriptor方法

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor

所以您的情况可能如下所示:

if (compInstance.hasOwnProperty(prop) || 
    compInstance.hasOwnProperty('_' + prop) || 
    Object.getOwnPropertyDescriptor(compInstance.constructor.prototype, prop)) 

这说你必须初始化你的财产,如:

export class MyDynamicComponent { 
    text: string = '4'; 

这里是Plunker Example