Step into the future with Angular 11: Revolutionize your forms with multiple fields

Currently using angular 11 and encountering a challenge with implementing the following functionality: A stepper containing two inputs in a single step, specifically a datepicker and a select dropdown menu. The objective is for the stepControl to validate that both fields have been filled out and be able to retrieve their values.

While I have multiple steps in my example, it's this particular one that's causing issues.

HTML :

<mat-vertical-stepper>

   <!-- First steps... -->

   <mat-step state="date" [stepControl]="fourthFormGroup">
       <form [formGroup]="fourthFormGroup">
         <mat-form-field>
           <ng-template matStepLabel>Placeholder Text Date</ng-template>
           <input matInput [min]="minDate" [matDatepicker]="picker" [formControl]="date">
           <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
           <mat-datepicker #picker></mat-datepicker>
         </mat-form-field>

         <br/>

         <mat-form-field>
           <mat-label>Placeholder Text Hour</mat-label>
            <mat-select [formControl]="hours" required>
             <mat-option *ngFor="let j of hours" [value]="j[0]">
               {{j[1]}}
             </mat-option>
           </mat-select>
         </mat-form-field>
       </form>
       <div>
         <button mat-button matStepperPrevious>Back</button>
         <button mat-button (click)="searchNow()">Search</button>
        </div>
     </mat-step>

</mat-vertical-stepper>

TS declaration :

public fourthFormGroup: FormGroup;

TS in ngOnInit :

this.fourthFormGroup = this._formBuilder.group({
  date: new FormControl(new Date()),
  hours: new FormControl('', Validators.required)
});

Issue Faced :

The challenge lies in retrieving values from this form. Moreover, validation of the form when empty fields are present results in backend errors, which are not being visually indicated by the frontend-component as expected (such as highlighting the field in red and indicating it as required).

Your assistance is greatly appreciated! Kev'.

Answer №1

You may be encountering an issue due to mixing up the directives in your code. Trying to bind a [FormControl] to undefined values, like [formControl]='date', will certainly not yield the desired outcome.

To address this problem, make sure to change [formControl]='date' to formControlName='date' and formControl="hours" to

formControlName="hours"

For reference, check out this demo

Note:

I recommend using one formGroup for all input fields for a more organized approach:

  myForm = this.formBuilder.group({
    thirdFormControl: ['', [Validators.required]],
    date: [new Date(), [Validators.required]],
    hours: ["", [Validators.required]]
  })

Also, remember to update your HTML structure accordingly:

<form [formGroup]='myForm'>
    <mat-vertical-stepper [linear]="true" #stepper>
        <mat-step [stepControl]="step[0]" [optional]="true">

            <ng-template matStepLabel>Placeholder title</ng-template>
            <mat-form-field>
                <mat-label>Placeholder label</mat-label>
                <textarea
          matInput
          cdkTextareaAutosize
          #autosize="cdkTextareaAutosize"
          cdkAutosizeMinRows="2"
          cdkAutosizeMaxRows="10"
          placeholder="Optional"
          formControlName="thirdFormControl"
        ></textarea>
            </mat-form-field>
            <div>
                <button mat-button matStepperPrevious>Back</button>
                <button mat-button matStepperNext>Next</button>
            </div>
        </mat-step>

        <mat-step state="date" [stepControl]="step[1]">
            <mat-form-field>
                <ng-template matStepLabel>Placeholder label 0</ng-template>
                <input
          matInput
          [min]="minDate"
          [matDatepicker]="picker"
          formControlName="date"
        />
                <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>

            <br />

            <mat-form-field>
                <mat-label>Placeholder label 1</mat-label>
                <mat-select formControlName="hours" required>
                    <mat-option *ngFor="let j of hours" [value]="j[0]">
                        {{j[1]}}
                    </mat-option>
                </mat-select>
            </mat-form-field>
            <div>
                <button mat-button matStepperPrevious>Back</button>
                <button mat-button (click)="searchNow()">Search</button>
            </div>
        </mat-step>
    </mat-vertical-stepper>
</form>

This modification ensures that the form will be marked as invalid if any field is left empty or incomplete.

For a working example, you can view it 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

Having trouble selecting checkboxes in React Native

When working on React Native tests, I utilize react-native-paper. Below is the code snippet: {(!props.question.isSingleAnswer && props.question.answers.length) && <View> {props.question.answers.map((item) => ( ...

What are the advantages of using any type in TypeScript?

We have a straightforward approach in TypeScript to perform a task: function identity(arg) { return arg; } This function takes a parameter and simply returns it, able to handle any type (integer, string, boolean, and more). Another way to declare thi ...

Why does WebStorm fail to recognize bigint type when using TSC 3.4.x?

Currently, I am working on the models section of my application and considering switching from using number to bigint for id types. However, despite knowing that this is supported from TSC 3.2.x, WebStorm is indicating an error with Unresolved type bigint. ...

What is the best way to convert an array of Firestore DocumentReferences into an array of DocumentData?

Trying to create a Google Cloud Function that reads Firestore Documents from a collection and takes action based on these documents. The goal is to optimize efficiency by reading the documents once and storing them in an array to minimize read operations. ...

Is it possible to create and manage a hierarchical menu in React (Next.js) using a generic approach?

Over the past few days, I've been working on a project involving a navigation bar built with TypeScript and React (Next.js). Up until now, I've only had a single level navigation, but now I'm looking to upgrade to a multi-level navigation me ...

Issue with RxDB: Collection not found upon reload

Exploring the integration of RxDB in my Angular project. I wanted to start with a simple example: export const LANG = { version: 0, title: "Language Key", type: "object", properties: { key: { type: "string", primary: true } }, requ ...

Exploring the Power of Angular 5 with TypeScript and ES2015 Syntax

I have been working on an angular 5 application where I needed to incorporate the dmn-js library. Unfortunately, this library does not come with typings available. To tackle this issue, I followed the guidelines provided in the Angular-CLI wiki regarding h ...

Adding styles to specific child nodes within a p-tree component in PrimeNG

Starting off with a demonstration example: Check out this StackBlitz for primeng p-tree. I am utilizing primeng to construct a structure for polls and answers using p-tree. The hierarchy is as follows: Participants --> Polls --> Questions --& ...

Tips on integrating custom icons in Angular-Material through refactoring

To simplify the process of adding custom icons and using them in the mat-icon tag, you can follow this method that has been successful for me: private domSanitizer: DomSanitizer){ this.sessionService.currentLanguage = 'es'; const i ...

Automatically focus on the button

Encountering an issue where setting focus on a button upon the input key enter event is not working. While setting focus on inputs functions properly, using the same code on a button does not work at all. Sample HTML Component: <form [formGroup]=&apos ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

SlidingPane header in React disappearing behind Nav bar

Here is the code snippet from my App.js file: export class App extends React.Component { render() { return ( <BrowserRouter> <NavigationBar /> <Routes /> </BrowserRout ...

Include form data into an array of objects within an Angular data source

I am struggling to add the edited form data from edit-customers-dialog.ts into an array of objects in my datasource. The form.data.value is returning correctly, but I'm facing issues with inserting it properly into the array. As a beginner in Angular ...

Tips for implementing validators for both domestic and international phone numbers in Angular

Using the following code in a TS file, the first argument always works before the "||". However, only the regex needs to be manipulated. phoneNumber: ['', [Validators.required, Validators.pattern(('^[0]{1}[1-9]{9}$')||('^\&bs ...

Check out the uploaded file preview on React Native Expo!

I'm attempting to display a preview of the file uploaded by the user, which could be in pdf, img, or doc format. I tried a method that previews the file using a specific URL, but what I really want is for it to only show the preview of the uploaded fi ...

Every time I try to request something on my localhost, NextJS console throws a TypeError, saying it cannot read the properties of undefined, specifically '_owner'

Update: I've noticed that these errors only appear in Chrome, while other browsers do not show them. Recently, I created a simple NextJS project by following a couple of tutorials, which also includes TypeScript. However, after running npm run dev, I ...

Issue with Dropdown menu in Navbar on Bootstrap 5 when using ng add installation technique

Here's my current setup: I'm currently using Angular 11.2.11 and Bootstrap 5 on a Windows system. The project I'm working on utilizes SCSS. The Issue at Hand: I've been following the codes provided in the bootstrap documentation (whi ...

Utilizing Angular for Webcam Integration

After trying out this code snippet: <video autoplay playsinline style="width: 100vw; height: 100vh;"></video> <script> navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } }) .then(stream =&g ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

Troubleshooting: Resolving the error message 'Unable to assign to Partial<this>' within a subclass method

If I call the base class's update method using a subclass instance, it functions as expected. However, I encounter an error when attempting to do so within a subclass method: Argument of type '{ prop: number; }' is not compatible with par ...