Resolving a Form Group Challenge in Angular 9

Disclaimer: I am still learning about angular and TypeScript in general.

My goal is to create an activation component that can submit a code directly to the service if it's included in the URL parameter query. If the code is not in the URL, then the user should be able to input the code into a form and submit it to the service. The field should be disabled when there's a code in the URL query and enabled otherwise.

The current issue I'm facing has to do with submitting the code to the service, which is resulting in the following error:

ERROR TypeError: Cannot read property 'get' of undefined
at ActivationComponent.handleActivation (activation.component.ts:48)

Previously, I had this.validateform.value on line 48, but it led to the same error.

I've been trying different approaches for a while now and feeling a bit lost...

Here's what the component.ts looks like:

import {Component, Input, Output, EventEmitter, AfterViewInit, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {AuthService} from '../auth/auth.service';

@Component({
  selector: 'app-activation',
  templateUrl: './activation.component.html',
  styleUrls: ['./activation.component.scss']
})
export class ActivationComponent implements OnInit {
  // Component properties
}

And this is the current HTML structure:

<!-- HTML content -->

Answer №1

When you have the code in your constructor executed before the ngOnInit() method, the form is not initialized yet and you will encounter errors when trying to use it.

To fix this issue, simply rearrange the order of your subscription as shown below. This adjustment should address the problem:

constructor(private router: Router,
          private fb: FormBuilder,
          private activatedRoute: ActivatedRoute,
          private authService: AuthService) {

}

ngOnInit() {
  this.showModal = true;
  this.validateForm = new FormGroup({
    CODE: new FormControl({value: this.activationCode, disabled: this.isConfirmLoading}, Validators.required)
  });
  this.activatedRoute.queryParams.subscribe(params => {
    const code = params.code;
    if (code){
      this.isConfirmLoading = true;
      this.handleActivation(code);
    }
  });
}

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

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

You can obtain the values of multiple div selections using jQuery

In a display with two columns, I want to be able to perform a common operation (such as delete) based on the selection of certain div IDs. If a user selects the div IDs participant_1, participant_4, participant_6 at the same time, I need to collect these ...

Incorporating unique symbols into a RegExp object during its creation using a variable

As a beginner, I am currently working on a small function that will allow users to pick up objects and add them to an inventory by entering text in a box. In my setup, there is a text box with the id "commandBox" and a button that triggers the 'pickU ...

Issue observed: The app.module.ts file is missing from the src/app folder in the Angular project

While attempting to create a new Angular project, I've noticed that my app.module is not being generated. Despite updating my node version and npm, as well as examining anything else that might be causing the issue, the app.module still isn't app ...

Creating separate files for establishing DB connection and writing Node.js queries is a recommended practice for organization

Having an issue with connecting dbconnection.js and demo_api_select.js. When trying to declare a variable in demo_api_select.js, I am encountering errors like this: Error Notification Please assist me in resolving this problem. dbconnection.js: var ...

if the response from the AJAX request contains

I need to search for a specific word in the response text and then perform some actions based on that, but I am only getting a "true" response from PHP. How can I achieve this functionality? function checkCellNo() { var cellNumber = _("CellNo"). ...

Utilize Python 3.7 to mark a checkbox on an HTML webpage

I am currently attempting to use Python 3.7 and Selenium to select a checkbox on an HTML page. My ultimate goal is to manipulate these checkboxes, but I am struggling to even select them correctly. The URL in question is: Prior to seeking assistance here, ...

Tips for implementing constraints in Angular 8 route parameters

In my Angular web application, I am in the process of configuring routes with parameters. How can I add constraints to ensure only specific IDs are allowed? Below is the path defined in my 'app-routing.module.ts' file: {path: 'post/:id&apo ...

I am constantly encountering the error message "Reading 'Linear'' error due to undefined properties in my threejs code

A procedural generation library for threejs caught my attention Here is the link to the library: https://github.com/IceCreamYou/THREE.Terrain Despite following the instructions provided in the ReadMe.md file, I encountered an error that says: Cannot read ...

Encounter error message "Angular-CLI: Karma-Webpack fails due to 'file or directory not found'"

After initially starting with the classic Angular/systemjs setup for the Tour of Heroes, I transitioned to using angular-client. The application now performs well in both development and production modes, except for when I try to run tests using ng test. A ...

In JavaScript, there is a missing piece of logic when iterating through an array to find

I am working on a solution to populate empty values when data is not available for specific months. You can view my progress on Plunker here: http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview $scope.year = [ {"month":"mar", "val":"23"}, {"month":"feb", ...

Missing Values in jQuery Variable

I'm having trouble with adding a link after a block of text. Although the links render fine, the href tag seems to disappear. var eventstuff = data.text; var eventElement = $("<div class='well well-sm eventsWells'>"); var deleteButton ...

Share the constructor and enumeration in an npm module for exportation

My background in NPM and Node.js is limited, as my expertise lies mainly in JavaScript for web browsers. Recently, I created a JavaScript library that consists of a constructor function and an enum type. In JavaScript, enums do not exist natively, so the ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

Challenges with v-autocomplete in Vuetify.js

I am currently working with the v-autocomplete component and finding it somewhat rigid in terms of customization. I am hoping someone can provide some insight on this issue. Is there a way to have a default display text value in the input when the page fi ...

Showing an error message upon submission in Angular 4 according to the server's response

Struggling for hours to display an error message when a form submits and returns an error status code. The solution seems elusive... In the login form component below, I've indicated where I would like to indicate whether the form is valid or invalid ...

customize your selections in p-multiselect with dynamic choices primeng angular 2

I am currently working on implementing the Primeng datatable. I have put together an array containing headers, fields, and options called headersList. Here is how it looks: { header: "Time", field: "time", options: "timeOptions" }, { header: ...

Guide on implementing a check all and delete function using the datatables (jquery datagrid plugin)

I am currently utilizing the Datatables jQuery plugin to manage my table rows. While it comes with a tabletools plugin that allows for a checkall function, I am wondering how I can add a custom delete button and retrieve the selected row. Fortunately, I a ...

Exploring TypeScript's type checking functionality

I've been pondering about the concept of type guards in TypeScript, particularly regarding their necessity when only one type is defined in a method signature. Most examples in the TypeScript documentation focus on scenarios involving union types, lik ...

Execute a PUT request within a Firebase Cloud Function database handler

I am working on syncing data between my server's database and Firebase realtime db. The first part, which involves syncing from my server to Firebase, is already complete. However, I am facing challenges with the second part - syncing data from Fireba ...