The error message thrown is: "Unable to assign value to property 'formGroup' as it is not defined

There's a particular component structure as shown below:

import { Component, Input } from '@angular/core';
import { WorkingHours } from '../../../../../hours';
import { FormGroup } from '@angular/forms';

@Component({
  selector: '[app-working-hours]',
  templateUrl: './working-hours.component.html',
  styleUrls: ['./working-hours.component.scss']
})

export class WorkingHoursComponent {
  @Input() properties: { formGroup: FormGroup; workingHours: WorkingHours; index: number; period: string; };
  get formControls(): any { return this.properties.formGroup.controls; }

  constructor() {
  }
}

Additionally, there's a test case associated with the component:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';

import { WorkingHoursComponent } from './working-hours.component';
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';

describe('WorkingHoursComponent', () => {
    let component: WorkingHoursComponent;
    let fixture: ComponentFixture<WorkingHoursComponent>;

    beforeEach(async(() => {
        imports.push(ReactiveFormsModule);

        TestBed.configureTestingModule({
            imports: imports,
            declarations: [
                WorkingHoursComponent
            ],
            schemas: [NO_ERRORS_SCHEMA]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(WorkingHoursComponent);
        component = fixture.componentInstance;
        let fixed = new FormControl(false);
        let startTime = new FormControl('');
        let endTime = new FormControl('');
        component.properties.formGroup = new FormGroup({
          fixed,
          startTime,
          endTime
        });
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

However, an error is being encountered: TypeError: Cannot set property 'formGroup' of undefined Any assistance on identifying the issue would be highly appreciated. Thank you.

Answer №1

Since the property does not have a predefined value, give this a shot.

component.properties.formGroup = {
  formGroup: new FormGroup({
    fixed,
    startTime,
    endTime
  }),
  index: 0,
  period: 'period'
}

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

Make sure to wait for the observable to provide a value before proceeding with any operations involving the variable

Issue with handling observables: someObservable$.subscribe(response => this.ref = response); if (this.ref) { // do something with this.ref value } ERROR: this.ref is undefined How can I ensure that the code relying on this.ref only runs after ...

What is the best way to compare two JSON strings in Java while disregarding null values?

In my testing scenarios, I need to compare two JSON strings while disregarding null fields. Desired Output: { "field1":"value1"} Current Result and a Match Found: { "field1":"value1", "field2":null} Curr ...

Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies. In this specific scenario, I am interested in returning any validator errors in my response if they exist. Take a look at my SqlCompanyRepository.ts: async create(compan ...

Refine the observable data

Trying to filter a list of items from my Firebase database based on location.liked === true has been a challenge for me. I've attempted using the traditional filter array method but have not had success. Can anyone suggest an alternative method to acc ...

Differentiate between minimum and maximum values on ion-range sliders with discrete color options

I am currently working on customizing the theme of my ionic app, specifically trying to assign different colors to the min and max knobs on an ion-range component. At the moment, I am only able to apply a single HTML property called "color" to the selector ...

Ways to stop Google Places API from generating outcomes from a particular country

After carefully reviewing the entire documentation at https://developers.google.com/maps/documentation/javascript/reference/places-service#LocationRestriction, I am still unable to find a solution to my problem. I have successfully limited Google autocomp ...

Unable to open modal window in Angular 14 micro-frontend application

I've been working on a micro front end project and running into some issues with opening modal popup windows. I've tried both the Angular material and bootstrap approaches, but ran into problems with both. With Angular material, the popup window ...

Utilizing Angular to augment existing items in local storage

Hey everyone, I'm facing an issue with localStorage that I can't seem to figure out. I have a form where the first step collects name and gender, and the second step asks for weight and height. The data from step 1 is saved in localStorage, but ...

Typescript patterns for creating a modular library design

Transitioning a JavaScript project to TypeScript has been challenging for me, especially when it comes to establishing a solid design pattern for the library's modularity. Main Concept The core functionality of my library is minimal. For instance, i ...

Angular 4: Modifying the URL without the Component being Displayed

I'm currently facing an issue where I am attempting to link a component from one component using routerLink = "selected" const routes: Routes = [ { path: '', children: [ { path: 'account&apo ...

Implement Angular's Observable Subscription to fetch data from an API endpoint

Forgive me if I'm not using the correct terminology for Subjects and Observables. I am currently trying to subscribe to newImages in order to get a list of images. In my console, the response is as follows: [] [3] [7] [9] Each number represents ...

Generating a UTC timestamp in TypeScript

I am currently facing an issue with my application where I need to ensure that it always uses UTC time, regardless of the system time. I have a method in place to create a date: public static createDate(date: Date = new Date()): Date { return new Dat ...

How can one effectively monitor the progress of multiple ajax requests in Angular8 for optimal professionalism?

There is a single completed variable made up of 6 parts, outlined below: selectedCandidateData: Candidate = { candidateBasic: null, experienceList: null, educationList: null, certificationList: null, candidateAbout: null, }; Each part ...

Tips for quietly printing a PDF document in reactjs?

const pdfURL = "anotherurl.com/document.pdf"; const handleDirectPrint = (e: React.FormEvent) => { e.preventDefault(); const newWin: Window | null = window.open(pdfURL); if (newWin) { newWin.onload = () => ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...

Issue encountered while generating a fresh migration in TypeORM with NestJs utilizing Typescript

I am currently working on a Node application using TypeScript and I am attempting to create a new migration following the instructions provided by TypeORM. Initially, I installed the CLI, configured my connection options as outlined here. However, when I ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

Angular2 can enhance your webpage with a <div> element that covers the entire screen

While working on my Angular2 application, I encountered a challenging issue that I can't seem to resolve or find a solution for. Take a look at this image of my page: https://i.stack.imgur.com/b6KlV.png Code: content.component.html <app-header& ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Angular 6 tutorial: Creating a dynamic side navigation bar with swipe and drag functionality using Angular Material/Bootstrap

I am currently working on implementing a vertical swipeable/stretchable side nav-bar with angular-material in angular 6. However, I have encountered an issue with mouse interactions for stretching the nav-bar. Below is the code snippet: Here is the HTML c ...