Resetting clears the date default value

When the page is loaded, the date input field is automatically set to the current date. However, if the form is reset, instead of restoring the default date, the date field is cleared, as shown in the images below:

  1. Page load
  2. Form reset

// app.component.ts

export class AppComponent implements OnInit {
  currentDate: {};
  taskForm: FormGroup;
  taskArr: ITaskDetails[] = [];
  taskObj: ITaskDetails = {
    title: '',
    description: '',
    date: null
  };

  constructor(private taskSer: TaskService, private fb: FormBuilder) {
    this.currentDate = new Date().toISOString().substring(0, 10);
  }

  reset() {
    this.taskForm.reset();
  }
  ngOnInit() {
    // Initialising the form with default value for date input through form builder instance
    this.taskForm = this.fb.group({
      taskTitle: ['', Validators.required],
      description: [''],
      date: [this.currentDate, Validators.required]
    });
    console.log(this.taskForm);
  }

  onSubmit() {
    this.taskObj.title = this.taskForm.value.taskTitle;
    this.taskObj.description = this.taskForm.value.description ? this.taskForm.value.description : 'N/A';
    this.taskObj.date = this.taskForm.value.date;
    console.log(this.taskObj);

    this.taskSer.setData(this.taskObj);
    console.log({ ...this.taskObj });
    this.taskArr = this.taskSer.getdata();
    console.log(this.taskArr);
  }

// Form Template

The default value for the date input in this form template is not set through data binding. The form uses reactive form approach and sets the default value using the form builder instance.

  <form class="form-horizontal" [formGroup]="taskForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="title" class="col-sm-2 control-label">Title *</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="taskTitle" placeholder="Title of Task" formControlName="taskTitle" [ngClass]="{isValid: taskForm.get('taskTitle').valid, isInvalid: !taskForm.get('taskTitle').valid && taskForm.get('taskTitle').touched}">
        <span class="help-block" *ngIf="!taskForm.get('taskTitle').valid && taskForm.get('taskTitle').touched">Please enter the Task Title</span>
      </div>
    </div>
    <div class="form-group">
      <label for="description" class="col-sm-2 control-label">Description *</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="description" placeholder="Enter Your Description" formControlName="description">
      </div>
    </div>
    <div class="form-group">
      <label for="date" class="col-sm-2 control-label">Date of Completion *</label>
      <div class="col-sm-10">
        <input type="date" class="form-control" id="date" formControlName="date" [ngClass]="{isVaid: taskForm.get('date').valid, isInvalid: !taskForm.get('date').valid && taskForm.get('date').touched}">
        <span class="help-block" *ngIf="!taskForm.get('date').valid && taskForm.get('date').touched">Please chose a date for task completion</span>
      </div>
    </div>
    <div class="form-group">
      <div class="col-md-offset-5">
        <button type="submit" class="btn btn-default" [disabled]="!taskForm.valid">Submit your data</button>
        <button type="button" class="btn btn-default" [disabled]="!taskForm.touched" (click)="reset()">Reset Form</button>
      </div>
    </div>
  </form>

Answer №1

Resetting will restore the values to their original settings, with one exception - the date parameter relies on currentDate, which is not included in the default settings. To rectify this, include the following code:

  reset() {
    this.taskForm.reset();
    this.taskForm.get('date').patchValue(this.currentDate); //this line
  }

view demo

Answer №2

Another approach suggested by Vega is as follows:

resetForm() {
  this.taskForm.reset({date : this.currentDate});
}

Answer №3

Include this in your constructor:

constructor(protected detector: ChangeDetectorRef){}

Utilize the detector in your reset function to recognize the default setting

reset(){
   this.form.reset();
   this.detector.detectChanges();
   // set default value
}

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

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

Setting a global variable in the JavaScript code below

Is there a way to make the modal variable global by setting it as var modal = $("#modal"); ? The code snippet below includes the modal variable and is not functioning properly. It needs to work correctly in order to display: "Hello name, You have signed u ...

Reviewing a document within an npm module

Recently, I developed an npm package called test_package_cat that is designed to access a json file (info.json) at the beginning of its execution. This involves having both index.js (the main entry point) and info.json situated at the same level. When I e ...

Developing with TypeScript - Utilizing the <reference path="....."> directive

Recently, I encountered an issue while adding a plugin to the TypeScript compiler. After including my code and compiling tsc.ts, it compiled without any errors. However, when I attempted to run it, I noticed that some variables declared in io.ts were missi ...

Adding a JavaScript object into the $http service

Struggling to correctly insert an object in this format: $scope.newObj = {1: "N/A", 2: "KO", 3: "OK", 4: "OK", 5: "OK", 15: "N/A", 19: "OK"} An attempt was made using the following loop: var objt = $scope.newObject; console.log($scope.newObject[0] ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

How can we convert props into state once they have been initialized using GetDerivedStateFromProps?

Presented here is a straightforward Component design: export default class Editor extends Component { constructor(props) { super(props); this.state = { field: "Some Initial Text" }; this.handleChangeField = this.handleChangeField.bind(this ...

Interactive HTML button capable of triggering dual functionalities

I am working on a project where I need to create a button using HTML that can take user input from a status box and display it on another page. I have successfully implemented the functionality to navigate to another page after clicking the button, but I ...

What is the process for connecting controls to Canvas sprites?

Any input is EXTREMELY helpful! To put it shortly, I'm in need of assistance with utilizing HTML5/CSS3 buttons to manage sprite animations on my canvas. These buttons are responsible for controlling the direction and speed of the sprites independentl ...

Adjust hover effects based on true conditions

Currently working on a web app using HTML, CSS, JavaScript, and AngularJS. Progress so far includes a clickable box that triggers a javascript function to display more boxes upon click using ng-click. <div ng-click="!(clickEnabled)||myFunction(app)" cl ...

Retrieve the file from Amazon S3 and download it

I'm having an issue with downloading a file from a directory outside of the root. Whenever I try, it defaults to looking in the root directory. I need users to be able to download these files on my site. The file was initially uploaded to Amazon S3 a ...

Removing a database record with JQuery

I have implemented a PHP function that converts any 2D PHP array into an HTML table. Within the table, I want to include a delete button in each row. When the user clicks on the delete button, I need jQuery to extract specific fields (3 fields) and submit ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Is it possible to utilize AngularJS' ng-view and routing alongside jade?

Currently, I am diving into the world of the MEAN stack. I noticed that Express utilizes jade by default, but I decided to experiment with it even though I can easily use html instead. When attempting to route with Angular, like so: ... body div(ng-view ...

Managing values in Vue using v-model can sometimes lead to inconsistencies in value increment

When I try to increment or decrement the counter, my input shows a different value than what is in this.count. For example, when I increment the value, the input shows '3' but this.count === 2. Vue.component('product-item', { data: func ...

executing a javascript function in PHP following form submission

Having trouble calling a javascript function after submitting a form and experiencing errors? New to PHP and seeking assistance. Any advice is appreciated. if(!empty($varAccountType)) { <?php if($varAccountType=='Free Account') { ...

Troubleshooting Angular Karma Testing: Uncaught ReferenceError - Stripe not recognized

When running tests with karma, I encountered the following error: ReferenceError: Stripe is not defined Component import { Component, OnInit } from "@angular/core"; import { FormBuilder } from "@angular/forms"; import { Router } from & ...

Update to react version 18.2.0, router-dom v6, and mui 5 for improved performance

Struggling to convert the following file or code into React's latest version and react-router-dom v6. I attempted it myself but encountered errors related to createBrowserHistory that I couldn't comprehend. My routes are stored in a JSON file and ...

Encountering Next.js Hydration Issue when Using Shadcn Dialog Component

While working on a Next.js project, I came across a hydration error when utilizing the Shadcn Dialog component. The specific error message reads: "Hydration failed because the initial UI does not match what was rendered on the server." Highligh ...

Tips for importing a json response into PHP

After successfully bringing all the results from fetch.php to my bootstrap modal HTML screen using JSON, I encountered a problem. I want to run a MYSQL query with a value from the same JSON used for the modal, but I'm unable to assign this value to a ...