Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding.

Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.component.ts. However, this approach did not yield the desired result.

// Form Template

<section class="container">
  <div class="panel panel-default>
    <div class="panel-heading">Add a Task</div<
    <div class="panel-body>>
      <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">
          </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" [value]="currentDate">
          </div>
        </div>
        <div class="form-group>
          <div class="col-md-offset-6">
            <button type="submit" class="btn btn-default">Submit your data</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</section>
<section class="container">
  <app-task-list></app-task-list>
</section>

// App component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  currentDate: {};
  taskForm: FormGroup;

  ngOnInit() {
    this.taskForm = new FormGroup({
      'taskTitle': new FormControl(''),
      'description': new FormControl(''),
      'date': new FormControl(null)
    });
    this.currentDate = new Date();
    console.log(this.currentDate);
  }

  onSubmit() {

  }
}

Answer №1

If the specified date format does not match what the form/input is expecting, the date will not be displayed. One option is to convert the date within your component or utilize a pipe.

Using a pipe:

<form>
  <input 
      type="date" class="form-control" 
      name="currentDate" [ngModel]="currentDate | date:'yyyy-MM-dd'">
</form>

Without using a pipe:

Component:

currentStringDate;
constructor() {
    this.currentStringDate = new Date().toISOString().substring(0, 10);
}

HTML:

<input type="date" class="form-control" name="currentStringDate" [ngModel]="currentStringDate">

edit: Remember to include the name attribute in your HTML and ensure that it matches the ngModel variable name.

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

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

How can we define a function using a generic type in this scenario using Typescript?

Here's a challenge that I'm facing. I have this specific type definition: type FuncType<T> = (value: T) => T I want to create a function using this type that follows this structure: const myFunc: FuncType<T> = (value) => valu ...

PHP Login Script that features Ajax loading of the Header directly on the page itself

I am encountering a challenge with my PHP login script and AJAX implementation. The PHP script successfully redirects the user to a page upon successful login, but when using the AJAX request, the header location loads inside the $('.logresult') ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

There is no such property - Axios and TypeScript

I am attempting to retrieve data from a Google spreadsheet using axios in Vue3 & TypeScript for the first time. This is my initial experience with Vue3, as opposed to Vue2. Upon running the code, I encountered this error: Property 'items' does ...

"Encountering issue with auto-import suggestions failing to appear in VS Code version 1.88.0

After installing the necessary libraries for MUI, I encountered an issue where basic components like Typography were not showing up in intellisense. Instead, it was displaying @mui/icons-material. You can view screenshots below: https://i.stack.imgur.com/ ...

ngx: navigate to the specified URL once the user has been successfully logged in

I am faced with a dilemma where I must wait for my authentication server to return my token before calling my APIs. I am looking for a solution to ensure that my authState.token is not null before dispatching LoadMyStuffFromApi. I have implemented two res ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

Error encountered with default theme styling in Material-UI React TypeScript components

Currently, I am working on integrating Material-UI (v4.4.3) with a React (v16.9.2) TypeScript (v3.6.3) website. Following the example of the AppBar component from https://material-ui.com/components/app-bar/ and the TypeScript Guide https://material-ui.com/ ...

Receiving 'Module not found' error in Typings on specific machines within the same project. Any suggestions on how to troubleshoot this issue?

I have a project cloned on two separate machines, each running VS2015 with Typings 1.8.6 installed. One machine is running the Enterprise version while the other has the Professional version, although I don't think that should make a difference. Inte ...

Trouble with updating data in Angular 8 table

In Angular 8, I have created a table using angular material and AWS Lambda as the backend. The table includes a multi-select dropdown where users can choose values and click on a "Generate" button to add a new row with a timestamp and selected values displ ...

What is the best way to send two separate properties to the selector function?

My selector relies on another one, requiring the userId to function properly. Now, I want to enhance the selector to also accept a property named "userFriend". However, there seems to be an issue with passing this new parameter, as it only recognizes the ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

Troubleshooting the inclusion of nodemon in package.json

I am interested in implementing nodemon to automatically recompile the project when there are changes made to the code during development. package.json { "name": "insurance-web-site", "version": "0.1.0", " ...

What is the most efficient way to retrieve 10,000 pieces of data in a single client-side request without experiencing any lag

Whenever I retrieve more than 10 thousand rows of raw data from the Database in a single GET request, the response takes a significant amount of time to reach the client side. Is there a method to send this data in smaller chunks to the client side? When ...

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

Common problems encountered post Typescript compilation

I encountered the same problem. Below is my tsconfig settings: "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "newLine": "LF", &q ...

Unit Testing Angular: Passing FormGroupDirective into a Function

I am currently writing unit tests for a function that takes a parameter of type FormGroupDirective. I have been able to test most of the logic, but I'm unsure about what to pass as a parameter when calling the resetForm() function. Here is the code sn ...

How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all ...