如何让ngModel使用动态getter/setter属性



我正在开发一个项目,该项目允许用户动态创建应用程序,为此,我允许组件像这样澄清自己的属性。

export class InputComponent extends GenericComponent implements OnInit {
ngOnInit(): void {    
// Test to check dynamic property works (it does)
(<any>this).Value = 499;
}
static availableProperties : PropertyDetails[] = [
new PropertyDetails({ label: "Name", type: "String", maxLength: 50, allowBlank: true }),
new PropertyDetails({ label: "Value", type: "Any" })
];
get availableProperties() : PropertyDetails[] {
return InputComponent.availableProperties;
}
}

然后,一个基本组件为这些属性创建动态getter/setter,这使我能够为这些属性分配值,而无需键入一些组件稍后可能具有的属性负载(或者可能是动态分配的(。基本的GenericComponent组件基本上看起来与此类似,并处理动态属性的设置。

export abstract class GenericComponent implements OnDestroy, ComponentInterface {
constructor() {
(<ComponentInterface>this).availableProperties.forEach((item : PropertyDetails)=> {
// Create customer getter / setters for this property
Object.defineProperty(this, item.label, {
get : function() : any {
return this.getProperty(item.label);
},
set : function(value : any) : void {
this.setProperty(item.label, value);
}
});
});
}

如果在TS代码(例如(中设置值,则此操作正常

(<any>this).Value = 499;

但它不会在ngModel 中分配这些动态属性

<input mat-input [(ngModel)]="Value" />

返回此暂停编译

Property 'Value' does not exist on type 'InputComponent'

有没有办法绕过这个问题,也许可以通过一些提示,比如//ts忽略,或者我必须在组件的结构中创建这些属性?

只使用GenericComponents的getProperty((和setProperty((并拆分ngModel绑定

<input mat-input [ngModel]="getProperty('Value')" (ngModelChange)="setProperty('Value', $event)" />

最新更新