Reputation: 61
I'm working on a project that lets users dynamically create applications, to do this I allow components to clarify their own properties like so.
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;
}
}
And then a base component creates dynamic getters/setters for these properties, this allows me to allocate values to these properties without typing a load of properties that some components may have later on down the line (or maybe allocated dynamically). The base GenericComponent component basically looks similar to this and handles the setting up of the dynamic properties.
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);
}
});
});
}
This works ok if setting the value in the TS code e.g.
(<any>this).Value = 499;
But it won't assign these dynamic properties in ngModel
<input mat-input [(ngModel)]="Value" />
Returns this halting compilation
Property 'Value' does not exist on type 'InputComponent'
Is there a way of getting around this, maybe via some hints like //ts-ignore or am I going to have to create these properties in the structure of the component?
Upvotes: 0
Views: 1213
Reputation: 61
Managed to just use the GenericComponents getProperty() and setProperty() and splitting out the ngModel binding
<input mat-input [ngModel]="getProperty('Value')" (ngModelChange)="setProperty('Value', $event)" />
Upvotes: 1