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

How can we optimize component loading in react-virtualized using asynchronous methods?

In my component, I have implemented a react-virtualized masonry grid like this: const MasonrySubmissionRender = (media: InputProps) => { function cellRenderer({ index, key, parent, style }: MasonryCellProps) { //const size = (media.submiss ...

Angular - Is there a specific type for the @HostListener event that listens for scrolling on the window?

Encountering certain errors here: 'e.target' is possibly 'null'. Property 'scrollingElement' does not exist on type 'EventTarget'. What should be the designated type for the event parameter in the function onWindow ...

Encountering a common issue: Angular 6 and aws-amplify network error issue

I am currently developing an app using Angular 6 and aws-amplify/aws-amplify-angular, where I am attempting to perform a HTTP GET request. However, I keep encountering a generic Error: Network Error message. This error can apparently be caused by various i ...

Mastering the art of mocking modules with both a constructor and a function using Jest

I'm a Jest newbie and I've hit a roadblock trying to mock a module that includes both a Class ("Client") and a function ("getCreds"). The Class Client has a method called Login. Here's the code snippet I want to test: import * as sm from &ap ...

Unable to fetch packages from npm or github using jspm install because of proxy configuration restrictions

I'm attempting to execute a basic Angular 2 unit test application. I have cloned the following git repository and followed the steps provided in the readme file: https://github.com/matthewharwood/Hit-the-gym I have configured proxy settings for npm, ...

Dynamic Mat-select-trigger that automatically adjusts its size to fit the content

Currently, I am experimenting with an Angular Mat-Select that allows multiple selections. To display the selected values in the value field, I have implemented a custom Mat-Select-Trigger. My goal is to enable automatic resizing of the value field (similar ...

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

Should we use fakeAsync() or done() to handle asynchronous tasks

When creating an Angular test with Jest and dealing with asynchronous operations, do you have a preference for how to handle it? it('', fakeAsync(() => { // test code here })); or would you rather use something like it('' ...

Contrary to GraphQLNonNull

I am currently working on implementing GraphQL and I have encountered a problem. Here is an example of the code I wrote for GraphQL: export const menuItemDataType = new GraphQL.GraphQLObjectType({ name: 'MenuItemData', fields: () => ...

Tips for sending properties to a child component in a React Native project using TypeScript

Here is the setup in my parent component: const [OTPNotify, setOTPNotify] = useState("flex"); const closeOTPNotify = () => { setOTPNotify("none"); } <OTPRibbonComponent onCancel={closeOTPNotify} display={OTPNotify}/> Now, ...

Implementing ETag in Angular 2

Implementing the odata standard which utilizes ETag has presented a challenge for me, particularly with PATCH requests. Each PATCH request requires sending the ETag in the header as If-None-Match. A HTTP status of 200 indicates that the change was successf ...

Accelerated repository uses TypeScript to compile a node application with dependencies managed within a shared workspace

Struggling to set up an express api within a pnpm turborepo workspace. The api relies on @my/shared as a dependency, which is a local workspace package. I have been facing challenges in getting the build process right. It seems like I need to build the s ...

Testing Angular Service Calls API in constructor using Jasmine Test

My service is designed as a singleton, and its constructor initiates an API call function. This simplifies the process during service initialization, reducing the complexity and dependencies on various components like AppComponent to import and execute API ...

Subject.next() not triggering Observable on value change

I'm currently working on developing an autocomplete feature using Observable and Subject in Angular. However, I've run into an issue where the service method is not triggered when the Subject object's value changes. Below is a snippet of my ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Creating a unique optional string array interface in TypeScript

I am looking to create an interface that includes optional string values. Here is what I have in mind: interface IEntity { values: ['RemainingUnits', 'ActualUnits', 'PlannedUnits'] } However, when implementing this inter ...

Use Filterpipe within Angular Template to sort content based on Object Value

I have an Object Mockup: export const IMAGES: Image[] = [ { ID: 1, NAME: 'Werk1', YEAR: 1992, IMGURL: 'assets/Images/1/img1.jpg', MATERIA ...

declaration of function interface and property that cannot be modified

After reviewing some new TypeScript code, I encountered a part that left me puzzled. interface test { (a: number): number; readonly b: number; } While I understand that (a:number): number signifies a function where the argument is a:number and the ret ...

Using Angular and RxJS5 to refresh data from both HTTP requests and sockets

Here's a specific scenario I need to address: Retrieve route parameters Utilize route parameters to make an HTTP service call Upon receiving a response from the HTTP service, use the same route parameters to invoke a socket service Whenever the sock ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...