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

Can you iterate through two arrays to find common values?

Upon examining my firebase database, I found the following structure: Users { askdfasdf: John: { Selection: [1,2,3] }, fasfadffe: Mark: { Selection: [1,2,4] } } Players { { name: &apos ...

Clicking the button to send the form using JavaScript

Currently, I am dealing with a shopping cart plugin that relies on a basic form on the product page to send values such as price and product name. However, I am facing an issue where this plugin uses a standard submit button to transmit the values, and I w ...

Utilizing TypeScript to invoke a method via an index signature

Here is a snippet of my code, where I am attempting to call a method using an indexed signature. It functions properly when the function name is manually added, but how can I call it using object notation for dynamic calls? createFormControl(formControls: ...

Transforming JavaScript statements and functions inside parentheses to make them React compatible

I'm struggling to understand the meaning and function of this parenthesis statement. Can someone provide clarity? function fadeOut(el){ el.style.opacity = 1; (function fade() { <-- Is this responsible for continuous execution? ...

A guide on displaying an array object in a table column using Vue.js and Element UI

Having issues with rendering array data in Vue Js Element UI using the el-table-column element. The string data displays correctly, but I'm facing problems with the array data. I've attempted to include static data within the data() return method ...

Can JavaScript trigger an alert based on a CSS value?

Hello, I am facing an issue. I have created a blue box using HTML/CSS and now I want to use JavaScript to display an alert with the name of the color when the box is clicked. Below is my code: var clr = document.getElementById("box").style.background ...

Using Database Data in a Material UI Select Component

I'm having trouble populating a select component from Material UI with data retrieved from my database. Although I can display the data in the component, upon selecting an option it breaks and displays the error "categorias.map is not a function". Any ...

every cell should be painted a distinct hue

I need to create a 10x10 array in JavaScript and fill each cell in the 2D array with different colors using canvas. I have managed to do this part, but now I am stuck on how to check if each cell has a different color from its neighbors. Any suggestions ...

Error encountered in the options of the Wordpress theme

While working on creating a custom theme options page for a Wordpress theme, I followed this tutorial: Initially, everything was going smoothly until I integrated the color picker function and script. Subsequently, whenever I tried to access the theme opt ...

Allow the NodeJS application to conduct self-updates using the NPM package manager

Hello, I'm currently exploring ways to add unique functionality to my NodeJS application, but I'm encountering some challenges. What I aim to achieve is as follows: I am interested in implementing a server code update feature from the client si ...

Exploring the Reach and Sequence of AJAX Callbacks

This particular piece of code aims to achieve three main tasks: 1) validate the online status of users, 2) retrieve their information from a slightly different URL, and 3) present both sets of data in HTML format. The implementation appears functional bu ...

Trigger a series of functions upon clicking with ReactJS

Need some assistance with an alert message functionality. I have a button labeled Checkout, and when clicked, it should clear the cart and display an alert. At present, the individual functions work as expected - calling emptyCart() works fine, and calling ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

What is the best way to empty input, select, and textarea fields after performing a clone operation

I am currently working on creating a form to display items and need a fresh text field when the user clicks the ADD button. function addNewItem() { //ADD ROW AND CLONE var table = document.getElementById('tbl'); var tbody = document.create ...

Running a JavaScript test using the Mocha framework with an 'import' statement for a JS file

I am familiar with the module.export and require method: Requiring external js file for mocha testing While it is useful when dealing with modules, I find it inconvenient as I now need to test code in a specific file. For example, I have code in a file: ...

What could be causing the poor performance of WebGPU in my benchmark when compared to WebGL?

After running my benchmark code on the Latest Chrome Canary on Win11 and disabling vsync with unlocked fps, I noticed that WebGPU has around 1/3 the FPS of WebGL. I'm struggling to understand the reason behind this performance difference. Here is the ...

Exploring the power of "this" in Vue.js 2.0

Seeking help with a VueJS issue. I am trying to create a voice search button that records my voice and prints it out in an input form. <input type="text" name="inputSearch" id="inputSearch" v-model="inputSearch" class="form-control" x-webkit-speech> ...

Utilize JavaScript to connect WhatsApp with the website

I am looking to use Javascript to enable opening WhatsApp on both iOS and Android devices. Below is the code I have attempted: window.open("https://wa.me/15551234567"); window.open("https://api.whatsapp.com/send?phone=15551234567"); ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Using an Angular variable with routerLink functionality

Is there a way to concatenate an id in my routerLink? <a routerLink="['/details', {{data.id}}]"> </a> is not working for me. Any suggestions on how to achieve this? Thank you in advance ...