An optional field has been identified as ng-invalid

In my set-up, I have created a form group using reactive forms.

this.transactionForm = fb.group ({
      'location': [null, Validators.required],
      'shopper': [null],
      'giftMessage': [null],
      'retailPrice' : [0, Validators.required]
    });

Shopper and giftMessage are intended to be optional fields without the requirement for Validators.Required to be set on them. The remaining fields in the form are mandatory.

However, upon loading the page, all fields including the optional ones like shopper and giftMessage are initially marked as ng-invalid. This causes an issue when trying to submit the form as even the optional fields need to be filled in.

I'm puzzled as to why these optional fields are initially marked as ng-invalid. How can I ensure that the optional fields remain valid inside the form group?

For instance, this is how I've configured my select field:

<select [ngModel]="null" formControlName="shopper" style="margin-left:35px;" required>
            <option value="null" disabled selected>{{'SelectOption' | translate}}</option>
            <option *ngFor="let shopper of shoppers">{{shopper | translate}}</option>
        </select>

During runtime, I noticed that the following classes are added to the field:

class="ng-touched ng-pristine ng-invalid"

Attempted solutions included adding these lines to the constructor:

this.transactionForm.controls['shopper'].markAsTouched();
this.transactionForm.controls['shopper']..setErrors({incorrect: false});

Despite these efforts, the control continues to show as ng-invalid.

Answer №1

Give this a shot:

<select [formControl]="transactionForm.get('shopper')" >
  <option [value]="null">{{'SelectOption' | translate}}</option>
  <option *ngFor="let shopper of shoppers" [value]="shopper" >{{shopper | translate}}</option>
</select>

Answer №2

To exclude certain inputs in reactive forms, Angular allows you to specify that it should not consider them using

[ngModelOptions]="{standalone: true}"

Therefore, you have the option to include [(ngModel)] for your input while excluding formControlName from it.

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 create a unique type in Typescript for a callback that is void of any return value?

When it comes to safe callbacks, the ideal scenario is for the function to return either undefined or nothing at all. Let's test this with the following scenarios: declare const fn1: (cb: () => void) => void; fn1(() => '123'); // ...

Encountering a 404 error in Angular 9 when refreshing the browser

Encountering a 404 error when attempting to access mysite.com/menu directly, but no issues when navigating through the homepage and selecting the menu option. Tried implementing an .htaccess file following Angular documentation, yet problem persists. Cur ...

Changing row colors based on property conditions in Angular 4

Hey there! I'm fairly new to Angular 4 and I've been working on creating a p-dataTable. My goal is to change the color of each row based on the quantity property of my object. Specifically, if the quantity is less than 10, I want the row to be di ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

Is it feasible to mock a defined function in Typescript for a unit test scenario?

Currently, I am working on typescript code that compiles into javascript, gets bundled with rollup, and is utilized by a framework. This framework exposes a library to me in the global scope, taking the form of a function: fun({ prop1: number, ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

How to extract the first initials from a full name using Angular TypeScript and *ngFor

I am new to Angular and still learning about its functionalities. Currently, I am developing an Angular app where I need to display a list of people. In case there is no picture available for a person, I want to show the first letters of their first name a ...

Navigating through Angular2 notifications using router chaining

I am currently working on a simple application form where, upon submission, the user is redirected to another page. My goal is to display a success message when the submit button is clicked. The code snippet below functions as expected, but there is an is ...

What is the best way to update my list after deleting an item using promises?

I am facing an issue in my Angular application where I need to update a list after deleting an item, but I am unsure about how to achieve this using promises. delete(id: any) { this.missionService.deleteMission(id); // .then((res) => { // ...

Is there a way to stop Material UI from dulling the color of my AppBar when using dark mode in my theme?

When I use mode: "dark" in my Material UI theme, it causes the color of my AppBar to become desaturated. Switching it to mode: "light" resolves this issue. This is how my theme is configured: const theme = createTheme({ palette: { ...

Error encountered when trying to create a Google Calendar event using the Google Calendar API on a Google business account with writer access

Utilizing the Google Calendar API within my Angular 9 Web Application, I am attempting to create events on a Google Calendar in my G Suite domain. Within the G Suite Admin Console, I have granted the service account permissions for the scopes and I have ...

Exploring how Django utilizes sessions in conjunction with Angular's cookies while integrating with Django Rest

Looking for a comprehensive example demonstrating how Django Rest Framework can send a session key to Angular for storage as a cookie. I've been trying to figure this out for days... I have Django running on port 8000 and in Angular's ng serve, ...

Obtain the string value for the template variable

Trying to display a string literal if element.elementId is null or undefined. <div>{{String(element.elementId)}}</div> Encountering an error: TableBasicExample.html:6 ERROR TypeError: _co.String is not a function at Object.eval [as updat ...

Tips for bypassing arrow functions when sending prop values to another component?

**Stateful ApplicatorType Component** class ApplicatorType extends Component { public state = { applicatorTypes: ['Carpenter', 'Painter', 'Plumber'], applicatorTypesSelected: [], } public render() { allotedTypes = ( &l ...

Requirements for Method Decorators - The complete path of the class module using the decorator must be provided

Upon running the decorator (method decorators) function, we are provided with access to target, methodName, and descriptor. I am seeking the module path for target in this specific scenario. Essentially, I want the file path that points to the module that ...

Combining multiple Observables and storing them in an array using TypeScript

I am working with two observables in my TypeScript code: The first observable is called ob_oj, and the second one is named ob_oj2. To combine these two observables, I use the following code: Observable.concat(ob_oj, ob_oj2).subscribe(res => { this.de ...

The utilization of Angular 2 and the assignment of formControlName values within a

Why must learning Angular2 be such a challenge? <input type="text" formControlName="exposure" type="hidden"> <label>{{exposure}}</label> When I use the formControlName in the input, the value is correct. How can I retrieve the value of ...

Angular2 import functions properly on the Windows operating system, however, it encounters issues on the Linux

import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { User } from './../../class/User'; I am encountering the fol ...

What is the best way to reference a component variable property within its template without explicitly stating the variable name?

Suppose my component is managing an instance of the following class: class Person { firstName: string; lastName: string; age: number; } Is there a way to directly reference its properties in the template like this: <p>{{firstName}}</p> & ...

Guide on transforming an Angular 6 project into a Progressive Web Application (PWA)

Currently, my Angular 6 project is up and running smoothly. However, I am looking to integrate PWA into my existing application. When I execute the following command: ng add @angular/pwa The output displays: + @angular/<a href="/cdn-cgi/l/email-protec ...