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

Angular 4 HTTP Requests Failing to Retrieve JSON Data

I am currently working with the following method in my Typescript: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const params: string = [ `onlyActive=${onlyActive}`, `page=${page}` ].join('&&apo ...

Steps to automatically update a component when the button is clicked

Is there a way to change the displayed component in my parent component when clicking on a specific element? I currently have a pie chart component displaying by default but would like to switch it to another component with a different diagram when clickin ...

It appears that when importing from a shared package in lerna, the name must include "src" at the end for Typescript or Javascript files

I am currently working on a straightforward lerna project structure as shown below: Project | +-- packages | | | +-- shared | | | | | +-- src | | | | | +-- index.ts | | +-- someDir | | | +-- usesShared | ...

Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component. Within my code, I have stored an array of objects in a variable called productlist. In my previous controller, I initialized another empty array nam ...

Executing functions in TypeScript

I am facing an issue while trying to call a function through the click event in my template. The error message I receive is "get is not a function". Can someone help me identify where the problem lies? This is my template: <button class="btn btn-prima ...

Troubleshooting Angular2 Router: Version 3.0.0-alpha.8 - Issue with resolving parameters for provideRouter function

Encountering an issue while working on a project in angular2 with router version "3.0.0-alpha.8". The error message displayed during the loading of APIs states: Can't resolve all parameters for provideRouter: (?, ?) . Error : BaseException$1@http:// ...

Sending additional parameters through an HTTP request in Angular

I've created a service method in Angular 8 with an optional parameter. However, I'm encountering a compile time error that says no overload matches this call. The error seems to be at the return statement. Can anyone help me figure out what' ...

Ways to enforce a specific type based on the provided parameter

Scenario Background: // Code snippet to do validation - not the main focus. type Validate<N, S> = [S] extends [N] ? N : never; // Note that by uncommenting below line, a circular constraint will be introduced when used in validateName(). // type Val ...

Angular debounce applied exclusively to user input

In my Angular2 project, I have implemented a reactive form. Within one of my components, I am subscribing to the value changes of a form control with a debounce time of 500ms using the following code: myForm.get("myField").valueChanges.debounceTime(500).s ...

Angular - Ensuring the Quality of Your Code

After creating a new project in Angular using the command "ng new app" and running "npm test," I successfully completed 3 tests. How can I view these tests in Test Explorer in Visual Studio? Do I need to open the project differently since I usually use "Op ...

Refine specific unions by considering past values that have been used

Here's the scenario at hand: type Option = 'x' | 'y' | 'z' | 'w' type Inquiry = { query: string; choices: Option[]; defaultChoice: Option // here's where it gets tricky } I am looking to set the def ...

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Can multiple modules that are lazily loaded be active at the same time?

We're excited about our upcoming project that will feature a tab-based UI design. Each tab will represent a different feature module, loaded lazily to improve performance. Our goal is to allow users to switch between tabs seamlessly and keep previousl ...

I'm currently working on building a form with the Angular framework, but I'm facing a challenge in displaying all the

I am having trouble with my Angular form as I am only able to display two fields when the page is loaded. Code snippet from Component.html: <div class="card m-3"> <div class="card-body"> <form [formGroup]="surveyFor ...

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

TSLint HTML Report Summary

Currently working on generating an HTML report for the "TSLint" task. Successfully created a report for "JSHint" using a specific package after installation. Struggling to locate a similar reporter for TSLint. "npm install gulp-jshint-html-reporter --sav" ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Tips for utilizing callback function in Angular 4

I previously used the Google API to obtain a current address and now I want to incorporate a callback function in this process using Angular 4. How can I go about implementing it? let geocoder = new google.maps.Geocoder(); geocoder.geocode({ &ap ...

Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on Gi ...