Tips for utilizing ngModel with dynamic setter/getter properties

Currently, I am engaged in a project where users can generate applications dynamically. In order to achieve this, I allow components to specify their own properties as shown below.

export class InputComponent extends GenericComponent implements OnInit {
    ngOnInit(): void {    
        // Testing dynamic property assignment (successful)
        (<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;
    }
}

In this setup, a base component generates dynamic getters/setters for these properties. This approach enables me to assign values to properties without having to manually define numerous properties that certain components may require later on, potentially dynamically allocated. The foundation of the `GenericComponent` component looks somewhat like this and takes care of establishing the dynamic properties.

export abstract class GenericComponent implements OnDestroy, ComponentInterface {
    constructor() {
        (<ComponentInterface>this).availableProperties.forEach((item : PropertyDetails)=> {
            // Establish custom getter / setters for the 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 method functions properly when assigning values via TypeScript code such as:

(<any>this).Value = 499;

However, it encounters issues with assigning these dynamic properties using ngModel:

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

Resulting in compilation errors:

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

Is there a way to resolve this problem, perhaps through annotations like //ts-ignore, or do I need to manually create these properties within the component structure?

Answer №1

Successfully utilized the GenericComponents method getProperty() and setProperty() by separating the ngModel binding.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component. Child Component: //imports... @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.c ...

Does Angular 16 not provide support for the agm/core module?

Encountering an issue while using Angular 16 with AgmCoreModule. The error message reads: node_modules/@agm/core/lib/core.module.d.ts:25:22 [ng] 25 export declare class AgmCoreModule { [ng] ~~~~~~~~~~~~~ [ng] This indi ...

What is the best way to provide a parameter to the query function in an Angular service class?

This snippet of code was generated by jHipster. invoice.component.ts @Component({ selector: 'jhi-invoice', templateUrl: './invoice.component.html' }) export class InvoiceComponent implements OnInit, OnDestroy { loadAll() ...

Tips for Logging HTTP Communication Errors in Angular

When making an HTTP put call to update a record in my .Net MVC application, I have noticed that the controller's put logic is not being triggered as expected compared to other types of HTTP requests. I want to implement error handling by using the Ha ...

What could be causing this TypeScript class to not perform as anticipated?

My goal with this code snippet is to achieve the following: Retrieve a template using $.get(...), Attach an event listener to the input element within the template I am using webpack to transpile the code without encountering any issues. The actual cod ...

Internet Explorer is throwing unexpected routing errors in Angular 2

I have a spring-boot/angular 2 application that is working perfectly fine on Chrome, Safari, Opera, and Edge. However, when accessed through Internet Explorer, the app directly routes to the PageNotFound component. I have tried adding shims for IE in the i ...

Contrasting input: [] with the @Input() directive

Recently, I've begun exploring the world of child and parent component communication in Angular 4. In my research, I stumbled upon older videos that utilize the input: [] syntax instead of the now more prevalent @Input() syntax. Is there any distincti ...

Angular Jasmine Test: Anticipated the invoked spy to have been executed

Examining a confirmation dialog in Angular 8 has led to an interesting discovery: one test passes while others fail, even though they are quite similar. The tests being conducted are for three statuses: Approve, Reject, and Reset. Interestingly, the test f ...

Displaying a disabled div depending on the dropdown selection in Angular Material

My goal is to display filters in a dropdown after they have been selected. Currently, I have static disabled divs and a dropdown where filters can be selected. This is the dropdown: <mat-form-field> <mat-label>{{ 'supplier.showFilters&a ...

Include [op.and] in the Sequelize query object

I want to construct my Sequelize query object based on input parameters. It functions well for database keys, as shown in the example below: let query = { where: { id: 5 } } if (inputName) { query['where']['name'] = { nam ...

Tips for resolving the issue with the 'search input field in the header' across all pages in angular 5 with typescript

I currently have a search field in the header that retrieves a list of records when you type a search term and click on one of them. The search function utilizes debounceTime to reduce API requests, but I'm encountering an issue where the search doesn ...

Preserve data even after refreshing the browser in Angular

Is there a reliable method to preserve my data after refreshing my browser? I've experimented with rxjs behavior subject, but it hasn't worked for me. I prefer not to use local/session storage due to security concerns and best practices, especia ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

I am facing an issue with Nestjs where it is unable to resolve my dependency, despite the fact that it is readily available within the

Encountering the following error: Error: Nest is unable to resolve dependencies of the CreateGroupTask (TaskQueueService, GroupsService, ?, GroupNotificationsService, GroupRepository, Logger). Please ensure that the argument dependency at index [2] is avai ...

The Angular Cli seems to be having trouble loading a State property and its reducer within the ngrx store all of

Following some minor changes to my application, I encountered an issue with my ngrx store not loading properly. While most of the store properties are displaying as expected and even fetching API results through their reducers, I am noticing that a crucial ...

What could be the cause of error TS2339 popping up: "Property 'scan' is not recognized on type 'Subject<any>'?

UPDATE: It's come to my attention that there may have been a shift from chaining to piping in RxJS 6.x. Can anyone confirm? See more at: This is my introduction to working with RxJS streams. I'm attempting to create some basic ones, but encounte ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...

Encountering problems while building Angular and Dot Net Core 2.0 Integration

I am encountering an issue where I am unable to build the Angular template using Dot Net Core/Standard 2.0 After downloading Dotnet core 2.0 and VS 2017 15.3, I followed the setup wizard to create a simple "hello world" project. Additionally, I installed ...

Utilizing Angular 2 directives with just JavaScript, is there a way to access the current element?

I am currently working in Angular 2 using Javascript. Within a directive, I find myself needing to access the current element to make changes to the DOM. It's worth noting that I can't use the commonly used hashtag trick (#element) because ther ...