the form control values are null or have not been filled in

I am encountering an issue in my .ts file where I cannot retrieve the value of my form control; it is always null. The form consists of two simple controls: Start Date and End Date. I am attempting to extract the values of these dates in my backend .ts file. Despite the calendar associated with these controls popping up, it fails to display any dates. The calendar remains blank. Below is the snippet of my HTML code:

<div class="headerDiv">
  <div class="headerTopBanner"></div>
  <div class="headerLogo">
      <div class="logo"></div>
  </div>
  <div class="headerBottomBanner">

  </div>
</div>
<div class="maxContent">
  <div *ngIf="!Loaded">
    <i class="loadingIconSearch fa fa-refresh fa-spin fa-4x fa-fw"></i> <span class="loadingIconSubSection">Loading</span>
  </div>
  <div *ngIf="Loaded" >
    <form id="RecProject">
      <fieldset>
    <div class="row"  >
      <div class="col-md-2">
        <mat-form-field >
          <input formControlName="startDate" matInput [matDatepicker]="picker" placeholder="Start Date">
          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
          <mat-datepicker #picker></mat-datepicker>
          <mat-error >Start date is Required</mat-error>
        </mat-form-field>
      </div>
      <div class="col-md-2">
        <mat-form-field>
          <input formControlName="endDate" matInput [matDatepicker]="endpicker" placeholder="End Date">
          <mat-datepicker-toggle matSuffix [for]="endpicker"></mat-datepicker-toggle>
          <mat-datepicker #endpicker></mat-datepicker>
          <mat-error >End date is Required</mat-error>

        </mat-form-field>
      </div>
      <div class="col-md-2">
        <mat-form-field (keydown.enter)="$event.preventDefault()" >
          <input matInput placeholder="Total Records" formControlName="totalRecords">
        </mat-form-field>
      </div>
</div>
<div class="row">
  <div class="col-md-4">
    <div class="row margintop10">
        <div class="col-md-12">
        <mat-form-field (keydown.enter)="$event.preventDefault()" class="fullWidth">
          <input matInput placeholder="DB Name" formControlName="DBName">
        </mat-form-field>


</div>
    </div>
  </div>
</div>
<div class="row">
<div class="col-md-5 inputMargin">
  <button class="appBtn lineButton" (click) = "LoadData()" >
    Start Loading
    <span><i class="fa fa-map-marker"></i></span>
  </button>
</div>
</div>


      </fieldset>
    </form>
  </div>

My .ts code for fetching the values of start date and end date is as follows:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import {RecLoadService} from '../shared/RecLoad.service';
import {RecLoadDataTypeModel} from '../Models/RecLoadData.model';

@Component({
  selector: 'app-Recload',
  templateUrl: './Recload.component.html',
  styleUrls: ['./Recload.component.css']
})
export class RecloadComponent implements OnInit {
  public Loaded = true;
  DataUploaded = false;
  message = null;
  public RecLoadData:RecLoadDataTypeModel=null;


public startDate = new FormControl('', Validators.required);
public endDate = new FormControl('' , Validators.required);
  constructor(public service: RecLoadService) { }

   ngOnInit() {
  }




  LoadData() {
     if (!this.startDate.hasError('required') && !this.endDate.hasError('required')) {
            this.RecLoadData.startDate  = this.startDate.value;
            this.RecLoadData.endDate = this.endDate.value;
           this.service.UploadRecLoadData(this.RecLoadData).subscribe(() => {
              this.DataUploaded =true;
              this.message = 'Data uploaded Successfully';

           });



       }
 }


    }

Upon running the code in Chrome browser, the start date and end date values persist as empty strings. Furthermore, the calendar associated with these controls displays no dates, remaining entirely blank. Please see the image below:

https://i.sstatic.net/Mf0n3.png

Any assistance on this matter would be greatly appreciated.

Answer №1

When developing systems, encountering problems is inevitable. The key is to find effective ways to troubleshoot and resolve issues in order to progress and receive payment for your work. Utilizing versioning can help save your code and provide a safety net as you tackle challenges head-on. Simplifying the problematic part of your code and focusing on what truly matters is essential for overcoming obstacles. Seek out examples and samples to guide you in the right direction.

To further enhance your knowledge, explore the documentation on Material form fields here.

While it may not seem immediately useful, this insight could prove invaluable in navigating future coding dilemmas. Pay attention to the messages from both your integrated development environment (IDE) and web console for additional clues.

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

Error encountered when attempting to utilize Path Aliases in Angular 11.tsconfig

Currently, I am working on a project using Angular 11 and aiming to utilize short imports like import {smthg} from '@common' instead of import {smthg} from '../../../common' However, I keep encountering errors in IDEA: TS2307: Cannot f ...

Tips for setting default values on Angular environments

For my Angular application, I have multiple environment files: environment.ts environment.dev.ts environment.prod.ts Instead of duplicating default variables in each file, I want to have them shared across all environments. For example, if I define a va ...

Issues with Angular Form Builder's Form Control not updating when invalid, causing errors with ngIf statements

I am encountering an issue where the error division fails to appear when the validator is invalid. The problem seems to be originating from this line: <div class = "danger" *ngIf="firstName?.invalid && (firstName?.dirty || firstName?.touched) ...

Exploring the dynamics of parent and child components in Angular

I'm currently working on an Angular2 project and I've hit a roadblock with the parent/child component interaction. My goal is to have a "Producer" entity that can have multiple "Products". Ultimately, I aim to retrieve lists of products associat ...

Having trouble running npm install while using a public wifi network?

Recently, I purchased a new laptop with Windows 10 and successfully installed nodejs along with angular 10. However, I encountered a problem when attempting to run ng new myproject, as it took an incredibly long time to install dependencies and seemed to h ...

Tips for determining the return type when a function yields various promise types

A scenario in which a function returns a Promise with two different potential types based on the parameters passed to it: async function myFunction(buf: boolean): Promise<Buffer | string> { const bytes = "00"; if (buf) { ret ...

The data from Angular2 Observable Subscription appears undefined, although a closer look at the Browser Debug reveals otherwise

Is it possible there is an issue with the data subscription process? Upon subscribing to data from a service call, 'undefined' is returned as the data set. Surprisingly, when I debug the code in the browser, it clearly shows that the correct dat ...

Different methods to initiate multiple calls using the dispatch function within ngrx

Utilizing NGRX to dispatch the IDs from an array, I am facing the challenge of needing to make multiple simultaneous calls instead of looping through them in ngOninit. Here is the code snippet for dispatch: loadEmloyeePricing(): void { let id = []; ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

What are the steps to integrate the TawkTo JS API into an Angular application?

I'm running into some challenges trying to implement the TawkTo JS API within my Angular application. Can anyone provide guidance on how to effectively integrate it? ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

Instructions on how to reset or restore to the initial spawn point

I am currently attempting to simulate a spawn process using the mock-spawn module. However, I am encountering issues with restoring the mock after running subsequent tests. I attempted to use mySpawn.resotre(), but it appears that this function does not e ...

Access a .docx file on my device by utilizing the Microsoft JavaScript API

In my current project, I am developing a Microsoft Word add-in using TypeScript, React, and the Word API. One of the key features of this add-in will allow users to open a document located on their computer, such as "C:\Test\Test.docx", with just ...

The declaration file for the datepicker module could not be located, even though the necessary types have been installed

I'm encountering an issue during production build on my Next.js project. The error message reads: Could not find a declaration file for module 'react-datepicker'. '../node_modules/react-datepicker/dist/index.js' implicitly has an ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

Front-end Angular cannot find the root using findByKey in the back-end

After successfully testing my findByKey() function in the back-end using Postman, I encountered an issue in the front-end services where I could not return an object. Instead, it would return an observable every time I console.log. Sample 1: Back-end root ...

Tips for utilizing express in your typescript projects

I'm curious about the transition of definition files from tsd to typings, and now to @types. How can I incorporate @types in a node/express project? What is currently preferred and what's the reason for moving from tsd to typing and finally to @t ...

Cleaning arrays in Angular 2 forms: A step-by-step guide

Need some assistance. I'm developing an app in Angular2(4) which includes a Form with 2 select boxes and 1 checkbox. My goal is to establish a dependency between these boxes using the following array: dataJSON = [ { productName: 'Produ ...

Having trouble launching myapp on the Android Studio emulator for Ionic 3

My current project involves using Ionic with Cordova to develop an app without any visible errors in the CLI. I am also utilizing Android Studio to emulate the app. In addition, I am relying on the Chrome inspect feature to monitor my app's behavior ...