Merge two input fields into one to send data to the backend

I have created two input fields, one for selecting a date and the other for entering a time. Before submitting the form to the backend, I need to combine these two inputs into one variable. For example,

<input type="text" name="myDate">
and
<input type="text" name="myTime">
should be combined to create a new variable called myDateTime.

Below is an example code snippet and a demo showcasing this functionality.

HTML

<form  [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate>
    <div  class="form-group">
        <div class="date-ctrl">
            <label> Date</label>
            <input class="form-control short" [(ngModel)]="myDate" matInput [matDatepicker]="picker"
                   (dateInput)="addEvent('input', $event)" [ngModelOptions]="{standalone: true}">
            <mat-datepicker-toggle class="img-calendar" matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </div>
        <div class="time-ctrl">
            <label> Time</label>
             <input class="form-control shot" [(ngModel)]="myTime" />
        </div>
    </div>

    <div class="footer-dialog">
        <div class="field-bottom">
            <span class="ctrl-button">
                <button class="dialog-button save-color" mat-button type="submit">Save</button>
            </span>
        </div>
    </div>

</form>

Component

createForm() {
      this.form = this.formBuilder.group({
          myDate: [''],
          myTime: ['']
      });
      // const myDateTime = myDate + myTime
  }

  onSubmit() {
      console.log(this.form.value)
  }

Click here for a live demo for further reference.

Answer №1

After analyzing your original stackblitz demo (which appears to be quite broken), I have managed to fix it sufficiently to showcase the functionality you are seeking:

datepicker-filter-example.ts:

    import {Component, OnInit} from '@angular/core';
import {
  FormControl,
  FormBuilder,
  FormGroup,
  Validators,
  FormGroupDirective,
  NgForm
} from "@angular/forms";

/** @title Datepicker with filter validation */
@Component({
  selector: 'datepicker-filter-example',
  templateUrl: 'datepicker-filter-example.html',
  styleUrls: ['datepicker-filter-example.css'],
})
export class DatepickerFilterExample implements OnInit {

  constructor(private formBuilder: FormBuilder){}
  public form: FormGroup;
  dateFilter = (d: Date): boolean => {
    const day = d.getDay();
    // Prevent Saturday and Sunday from being selected.
    return day !== 0 && day !== 6;
  }

  ngOnInit():void{
    this.createForm();
  }

  addEvent(v1:any, v2: any){
    console.log('Add Event Called');
  }

  myFilter(d: Date): boolean {
        const day = d.getDay();
    const month = d.getMonth();
        const todays_date = d.getDate();
        const todaysDateObject = new Date();
        const today = todaysDateObject.getDate();
    const actualMonth = todaysDateObject.getMonth();
    console.log(todays_date)

        /** Prevent actual system date from being selected.*/
    if (month === actualMonth && todays_date === today) {
      return false;
    } else if (day !== 0 && day !== 6) {
      return true;
    } else {
      return false;
    }

        /** Prevent Saturday, Sunda.*/
//        return day !== 0 && day !== 6;
    }



 createForm() {
      this.form = this.formBuilder.group({
        myDate: new FormControl(),
        myTime: new FormControl(),
      });
  }

  onSubmit() {
    const combined = `${this.form.get('myDate').value} ${this.form.get('myTime').value}`;
    console.log(combined);
  }

} 

datepicker-filter-example.html

    <form  [formGroup]="form" (ngSubmit)="onSubmit(form.value)"
    novalidate>

<div class="form-group">
    <div class="date-ctrl">
    <label>Date</label>
    <input class="form-control short" formControlName="myDate"  matInput [matDatepicker]="picker"
           (dateInput)="addEvent('input', $event)">
    <mat-datepicker-toggle class="img-calendar" matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</div>

<div class="time-ctrl">
    <label>Time</label>
    <input class="form-control shot" formControlName="myTime" />
</div>

</div>

<div class="footer-dialog">
    <div class="field-bottom">
        <span class="ctrl-button">
        <button class="dialog-button save-color"  mat-button type="submit">Save & Start</button>
        </span>

    </div>
</div>

</form> 

Answer №2

If you're looking to customize your form, here are a few options to consider:

  • Translate/map the form upon submission
  • Create a personalized form control for date and time input that links to a single value

It seems like you're interested in developing a custom form field.

For detailed instructions on how to design and implement Custom Form Controls, check out this informative article:

To seamlessly integrate these features with Angular Material, refer to the official documentation provided here:

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

Upgrade your @ngrx/store from version 10 to version 11 or 12

Hello there! I am in need of assistance regarding a specific issue. After updating our project to Angular 12 some time ago, I have been attempting to upgrade @ngrx/store from version 10 to either v11 or v12. Despite trying this update when we were still o ...

Having trouble with your Angular CLI project after attempting to duplicate it by copy and paste?

As a newcomer to Angular, I've recently embarked on creating a new project using the Angular CLI. Everything was going well until I decided to upload my work to GIT. After copying and pasting the project folder contents into another directory, I encou ...

When using Jest + Enzyme to test a stateful class component, encountering problems with Material-UI's withStyles functionality is a common issue

I have a React + TypeScript application with server-side rendering (SSR). I am using Material-UI and following the SSR instructions provided here. Most of my components are stateful, and I test them using Jest + Enzyme. Below is an example of one such com ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Submitting Angular data to PHP back-end is a common practice

I am attempting to send data from Angular to PHP. Angular POST Request var body = { "action":"getvouchernumber","vouchertype": vtype, "vmonth": vmonth, "vyear":vyear }; return this.http.post(this.BaseURI+& ...

Guide to implementing a specified directive value across various tags in Angular Material

As I delve into learning Angular and Material, I have come across a challenge in my project. I noticed that I need to create forms with a consistent appearance. Take for example the registration form's template snippet below: <mat-card> <h2 ...

Error: The jasmine framework is unable to locate the window object

Currently, I am testing a method that includes locking the orientation of the screen as one of its functionalities. However, when using Jasmine, I encountered an error at the following line: (<any>window).screen.orientation.lock('portrait&apos ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

Customizing Angular Material select fields with border radius

I attempted to adjust the select field by adjusting the border radius, but it doesn't seem to be taking effect. I've made changes in the general style.css file, but so far, the issue remains unresolved. ...

I'm really puzzled as to why they would choose to export in this manner in React

I noticed that several files were exported in a similar manner, and I'm unsure why this specific method was chosen. Could there be any advantages or particular reasons for exporting them like this? index.ts export { default } from './Something& ...

Learn the steps to translate conditional string interpolation with NGX-translate

My application has a toggle button that dynamically changes the label to either 'Enabled' or 'Disabled'. I am attempting to utilize ngx-translate for translation, but I am encountering difficulties in achieving this. Can anyone provide ...

Is it recommended to include modules in the Imports section of SharedModule in Angular?

Welcome to my SharedModule! import { CommonModule } from "@angular/common"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; import { IconModule } from "@my-app/components/icon/icon.module"; impo ...

Angular router.redirect is not able to pass variables as expected

I am facing an issue with the router redirect and template lifecycle while using Stripe checkout in my Angular 5 project. After a user signs up, I trigger the stripe checkout modal. Once the modal receives a payment source token, I perform some additional ...

Adding a static global constant in webpack dynamically

I'm facing a challenge with adding a global constant to my project using webpack.DefinePlugin. I've successfully added one in the module.exports, but I struggle to do this conditionally. When I declare and use '__VERSION__' in my module ...

Is it possible to verify if an object matches a type without explicitly setting it as that type?

In order to illustrate my point, I believe the most effective method would be to provide a code snippet: type ObjectType = { [property: string]: any } const exampleObject: ObjectType = { key1: 1, key2: 'sample' } type ExampleType = typeof ...

When attempting to access a static method in TypeScript, an error occurs indicating that the property 'users_index' does not exist on the type 'typeof UserApiController'

Just dipping my toes into TypeScript and attempting to invoke a function on a class. In file A: import userAPIController from "./controllers/customer/userAPIController"; userAPIController.users_index(); In file B: export default class UserApiControlle ...

Execute TypeScript on the Angular project's specified version

Is there a way to efficiently manage multiple projects on the same computer that require different versions of Angular? Can I specify the version of Angular within the package.json file to avoid conflicts? ...