Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with

"typescript": "~3.5.3"
. My objective is to handle the undefined collision in my code.

const { testLocation } = this.ngr.getState();
    this.step2 = testLocation && testLocation.step2 ? testLocation.step2 : {};
    this.$form = this.fb.group({
      email: [this.step2.email || '', [Validators.required, Validators.email, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')]],
      phone: [this.step2.phone || ''],
      configuration: this.fb.group({
        idTypesAccepted: this.buildIdentityDocumentTypeFormArr(this.identityDocumentType),

        sessionOpenDays: [this.step2.configuration.sessionOpenDays || '', Validators.required],
        sessionOpenHours: [this.step2.configuration.sessionOpenHours || '', Validators.required],
        sessionOpenMinutes: [this.step2.configuration.sessionOpenMinutes || '', Validators.required],

        sessionCloseDays: [this.step2.configuration.sessionCloseDays || '', Validators.required],
      sessionCloseHours: [this.step2.configuration.sessionCloseHours || '', Validators.required],
        sessionCloseMinutes: [this.step2.configuration.sessionCloseMinutes || '', Validators.required],

        applicationExpiryDays: [this.step2.configuration.applicationExpiryDays || '', Validators.required],
        applicationExpiryHours: [this.step2.configuration.applicationExpiryHours || '', Validators.required],
        applicationExpiryMinutes: [this.step2.configuration.applicationExpiryMinutes || '', Validators.required],

        paymentCloseDays: [this.step2.configuration.paymentCloseDays || '', Validators.required],
        paymentCloseHours: [this.step2.configuration.paymentCloseHours || '', Validators.required],
        paymentCloseMinutes: [this.step2.configuration.paymentCloseMinutes || '', Validators.required]
      })
    });

The issue lies in this.step2.configuration where configuration is currently undefined. To overcome this issue, I need to either fill it up with an empty value or a value from this.step2.configuration.

Answer №1

There are three possible approaches to handle this situation:

If the property is undefined, create a new dummy model object to override it.
this.step2 = testLocation && testLocation.step2 ? testLocation.step2 : {};
if(!this.step2.configuration) {
  this.step2.configuration = new Configuration(); // Dummy data model with empty/null variables;
}

Alternatively, you can duplicate the entire form building process:

if(!this.step2.configuration) {
  this.fb.group({
    sessionOpenDays: ['', Validators.required],
    [...]
  });
  return;
}
this.fb.group({[...]});

Another option is to switch to Angular 10 (or a newer version):

this.step2 = testLocation && testLocation.step2 ? testLocation.step2: {};
this.fb.group({
  sessionOpenDays: [this.step2.configuration?.sessionOpenDays || '', Validators.required],
[...]
});

In Angular 10, using the question mark operator in templates initializes the formControl with a null value if the property is not available. Keep in mind that direct calls to form fields will also return null instead of an empty string.

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

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Error in React JS: SyntaxError - "Unexpected token '?'"

Following the guidelines on this website, I successfully set up a new reactJS application, proceeded to run npm i && npm run dev and encountered the following error message: /home/www/node_modules/next/dist/cli/next-dev.js:362 showAll ...

Incorporate typings into your CDN integration

I'm interested in utilizing a CDN to access a JSON validation library, as it's expected to provide faster performance (due to retrieving the file from the nearest server within the CDN). The JSON validation library in question can be found here: ...

Clicking on a list item in React's material design will illuminate the item, marking it

I have 2 panels with a list group on each panel, following material design guidelines. Concern: When clicking the first list-item on panel 1, it does not get selected and change to style = "success", or highlight the selected item. The same issue occurs ...

Encountering an issue when utilizing a personalized directive with AngularJS

I'm encountering an issue with the "auto-complete" directive that I'm using from jsfiddle. The error message I'm receiving is iElement.autocomplete is not a function. Can someone help me troubleshoot and fix this error? directive.js starte ...

Retrieve user-specific relational data

In my Supabase database, I have three main tables: users, teams, and members. The users table stores information about all users who sign up using auth. Here are the details contained in this table: id displayname email 602eff1e-6300-491e-b821-44e ...

Using class binding for both ternary and non-ternary attributes

Suppose we have a tag that utilizes a ternary operator to apply alignment: <td :class="alignment ? ('u-' + alignment) : null" > This functions as intended since the pre-defined alignment classes are in place, now if we want to ...

Angular encountered an error: spawn UNKNOWN was not handled

Within my Angular-13 project, everything had been running smoothly. However, out of nowhere, I encountered an error when trying to run ng serve: An unhandled exception occurred: spawn UNKNOWN See "C:\Users\JOSHU~1.IBE\AppData\Local ...

What is the best way to extract valid objects from a string in JavaScript?

Currently, my data is being received through a TCP connection. To determine if a string is a valid JSON object, we use the following method: let body = ''; client.on('data', (chunk) => { body += chunk.toString(); try { ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

What steps need to be taken in VSCode to import React using IntelliSense?

When I press Enter in that image, nothing seems to occur. I believed IntelliSense would automatically insert import React from 'react'; at the beginning of the file. https://i.stack.imgur.com/7HxAf.png ...

Unexpected outcomes in linq.js

Hey there, I have a JSON object named "Faults" that looks like this: "Faults":[{"RoomId":1,"ElementId":173,"FaultTypeId":1,"Count":1,"Remark":""},{"RoomId":3,"ElementId":211,"FaultTypeId":7,"Count":1,"Remark":""},{"RoomId":4,"ElementId":173,"FaultTypeId": ...

Count the number of distinct values in an array of objects

Could you assist me with a JavaScript problem I'm experiencing? I have an array and need to extract the count key from the response. Here is a sample response: var events = [ ... I would like the array response to look like this: var events = [ ... ...

An issue has occurred in AngularJS where the error message "ng areq not

I'm facing an issue with my meta controller, as I am trying to alter the meta tags dynamically. When checking the console, I encounter the error message error ng areq not a function. I have looked on StackOverflow for similar issues but couldn't ...

Sending image to the server with the help of JavaScript

Curious if there is a method to upload an image to the server using javascript or jQuery and then save the image path/name into a database. I am working on a Windows platform server in asp.net 1.1, revamping a web page that is 10 years old. Unfortunately, ...

What is the best way to invoke a function that is saved in an array of options while using setTimeout() within an AJAX callback?

Below is the pertinent code snippet: success: [ setTimeout(function () { ajax.success }, 250), //... An interesting observation I made is that I am able to invoke ajax.success from inside the success ...

The child component fails to inherit the data types provided by the parent component

I am currently working on setting up a dynamic table that will receive updates from the backend based on actions taken, which is why I need to pass the endpoint and response model. When I try to nest and pass the response type, it seems to get lost in the ...

Issues with React in a Production Environment

After successfully developing a react app and express API that worked correctly in localhost, I decided to move my API to a digitalocean droplet. The droplet only had an IP address and used HTTP. While utilizing the API from the react app in development m ...

When you encounter an open response and need to resend it, simply click the "Send Again

After the discontinuation of Firebug, I find myself in need of two crucial functionalities that I used frequently. To replace these features, I am wondering if there are similar options available within the default Firefox Web Console. Previously, when ma ...

Bootstrap allows for the use of video backgrounds, offering the option for borders to be included

Having trouble with a Bootstrap HTML page featuring a video background? The issue is that sometimes the video has borders on the left and right, and occasionally on mobile devices as well. Oddly enough, when the browser (Chrome or Firefox) is refreshed, th ...