Setting the value of a class itself using a method in Typescript, inheriting from a base class

Is there a way to set the value of a class within its own method using this? I'm attempting to do so but encountering an error.

export class ProductForm extends FormGroup {

    constructor(){
      super({
        productName: new FormControl()
      })
    }
   
    addMoreFieldsTest(): void {
      this = {
        productName: new FormControl(),
        productDescription: new FormControl()
     }
}

Error: The left-hand side of an assignment expression must be a variable or a property access.

I could use AddControl method, however want to set class itself for learning purposes.

Answer №1

Revised Response

The FormControl's controls are not directly located within the FormGroup class, but rather inside a property called controls.

To add controls to the extending class, you can simply manipulate the controls property.

    export class ExtendedFormGroup extends FormGroup {
      constructor(
        controls: { [k: string]: AbstractControl },
        validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions,
        asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]
      ) {
        super({...controls, alwaysPresent: new FormControl()}, 
               validatorOrOpts, 
               asyncValidator
        );
        this.addExtendedProperties();
      }
    
      addExtendedProperties() {
        this.controls["additional_control"] = new FormControl("");
      }
    }

In summary:

  • Pass the constructor argument into the super method and include an additional always present control item.
  • Directly modify the controls property as stated in the original inquiry.

By creating a new instance of ExtendedFormGroup({}), you will now have a FormGroup with two predefined controllers: alwaysPresent and additional_control.

Prior Solution

JavaScript, and thus TypeScript, treat classes as labeled blocks with prototypes, allowing for square bracket notation to access properties within the class scope using this.

    class Parent {
      foo: string;
      constructor(foo: string) {
        this.foo = foo;
      }
    }
    
    class Child extends Parent {
      constructor(foo: string) {
        super(foo);
        this.assignPropertiesDirectly();
      }
    
      assignPropertiesDirectly() {
        this["bar"] = "Creates 'bar' on Child";
        this["foo"] = "overwrites foo with this text";
      }
    }

However, this approach is fragile and negates the advantages of TypeScript, relying on string-based property names which can lead to maintenance challenges or errors. Consider exploring composition design for a better solution.

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

Manifest for npm module

After releasing my first npm package, I realized that I needed to implement a declaration file ("*.d.ts") when integrating it into one of my projects. Despite multiple attempts, I have not been able to successfully integrate it and have spent days trying t ...

Unable to access the value property of null in Angular reactive form when attempting to retrieve the value

{ "estimate_number": "2020-1234", "brand": "PF", "floor": "Laminaat", "floor_type": "Normaal", "plint_type": "Hoog", "floor_installer": { "id": "14", "name": "Maestro" }, "address": { "street": "Straatnaam 19", "city": "Amst ...

The issue of ElementRef being undefined can arise when utilizing the @ViewChild directive

import {Component, ElementRef, HostBinding, ViewChild} from '@angular/core'; export class MainPage { constructor( el: ElementRef ) { this.contentElement = el.nativeElement; } contentElement = null; @ViewChild('wrapper' ...

Creating a clickable link within an element using router link in Angular 2

I'm facing a challenge where I want to include a router link on a div element, but also have an anchor or button inside that div to open a menu. Due to the router link, the menu cannot be opened as expected - instead, clicking on the button redirects ...

Error in Injecting Storage in Ionic 4: Provider Not Found

Currently, I am working with Ionic 4 and using node 8.x. My goal is to inject Storage into my app in order to retrieve a token from my authentication service. However, I am encountering the following error: StaticInjectorError(AppModule)[Storage]: Stat ...

Warnings are being generated when Angular 15 features multiple auxiliary routes in a specific module

I currently have 3 different router-outlets set up: primary router-outlet (detail) router-outlet (visited) All the routes are configured within the 'country' module. When you click on a country on the left side, you will see the details on the ...

ERROR Error: Uncaught (in promise): ContradictionError: The variable this.products is being incorrectly identified as non-iterable, although it

Seeking a way to extract unique values from a JSON array. The data is fetched through the fetch API, which can be iterated through easily. [please note that the product variable contains sample JSON data, I actually populate it by calling GetAllProducts( ...

Angular system.import script not able to execute properly

I am encountering an issue with my Angular2 application that I built in IntelliJ and Play Framework. The code snippet below is causing an error: <script> System.import('assets/app/main.js').catch(function(err){ console.erro ...

Ways to assign a default value to a radio button using a mock JSON dataset

As a beginner in AngularJS2, I am looking to resolve an issue where the checkbox is automatically checked when retrieving values from a mock JSON file. Can someone please help me? <div class="form-row"> <div class="formHeading">Skills *< ...

Angular-MongoDB CRUD Operations Simplified

After conducting an extensive search, I have come up short on resources that are best suited for my topic. My main query is how I can carry out CRUD operations directly from my Angular client to MongoDB. Although I have stumbled upon some discussions dis ...

Attempting to adhere to the prescribed Cypress tutorial is resulting in various errors related to being "compiled under '--isolatedModules'"

I am new to using Cypress and I have been following the helpful tutorial on testing your first application. However, I have encountered some compiler issues in the third section. Following the instructions, I created a custom command but I am receiving th ...

Unable to invoke Angular 6 router resolve - Component remains idle

Here is the resolution I have set for a specific route. @Injectable({ providedIn: 'root' }) export class CourseDetailResover implements Resolve<Observable<[Course, (Lesson[])]>> { constructor(private coursesService: Courses ...

Troubleshooting problems with styled and typed components in ReactJS

I created a styled component with the following structure: export const TestClassButton = styled(Button)({ ... }) Here is an example of how I implement it: <Tooltip arrow title={"status"}> <TestClassButton id={"button-statu ...

When utilizing typescript to develop a node module and importing it as a dependency, an issue may arise with a Duplicate identifier error (TS2300)

After creating a project called data_model with essential classes, I built a comprehensive gulpfile.js. This file not only compiles .ts to .js but also generates a unified .d.ts file named data_model.d.ts, which exports symbols and is placed at the root of ...

ngFor failing to properly update when new data is pushed

I am currently working on creating an array of reactive forms in Angular. Here is what I have set up: typesForms: FormGroup[] = []; In my HTML, I loop through this array like so: <form *ngFor="let type of typesForms; let i = index" [formGroup]="types ...

Converting object's date property to a new Date() in TypeScript

I am working with a CurrentWeather Model retrieved from localStorage and parsed into an object. export interface CurrentWeather { LocalObservationDateTime: Date; Latitude: string; Longitude: string; LocationKey: string; LocalizedName: s ...

Having trouble with adding elements to an array in Typescript

In the following code snippet, I am declaring an array within a class: pastq:number[]; randomqnumber:number; Inside an else statement within a function: this.randomqnumber=Math.floor(Math.random() * homework.length)+1; console.log(this.randomqnumb ...

Experience the power of Angular with seamless compatibility on all desktop devices

After hosting my angular application using ng serve --host IP_Address, I encountered an issue. Even though I can ping the machine and open the application from a virtual machine that remotely accessed the PC, I am unable to access it from my Windows mach ...

Notify the Angular frontend whenever there is a change in the state of the Node backend connected to MongoDB

Looking for a way to achieve real-time updates on Angular frontend when the state changes in MongoDB? What options do I have besides using socket.io? Imagine a scenario where a user creates a reminder and sets a date for an email to arrive in their mailbo ...

Loop through two arrays simultaneously using *ngFor in IONIC2/Angular2

Within the context of a single ion-list, I have populated two arrays with values to iterate through: Billerstatusstate and Billerstatusnamelst. I attempted the following iterations: <ion-list ion-item *ngFor="let stat of Billerstatusstate; let bil of ...