"Angular form's controls are valid but the form itself is marked

When creating a form group with existing values:

this.form = new FormGroup({
  field1: new FormControl(
    {
      value: obj ? obj.value : null,
      disabled: obj
    },
    Validators.required
  ),
  field2: new FormControl(
    {
      value: obj ? obj.value : null,
      disabled: obj
    },
    Validators.required
  )
});

Example: https://stackblitz.com/edit/angular-aadkss

My intention is to have the values filled, valid, and disabled when 'obj' exists, but currently they are being filled, disabled, and marked as invalid. How can I ensure that they are valid instead?

Answer №1

It is important to note that the values of .valid and .disabled are determined by the control's .status, which can only have one specific value. You can refer to the Angular documentation for more details: https://github.com/angular/angular/blob/f27deea003822ed46437e74f102b281f692b7811/packages/forms/src/model.ts#L191

/**
  * The validation status of the control. There are four possible
  * validation status values:
  *
  * * **VALID**: This control has passed all validation checks.
  * * **INVALID**: This control has failed at least one validation check.
  * * **PENDING**: This control is in the midst of conducting a validation check.
  * * **DISABLED**: This control is exempt from validation checks.
  *
  * These status values are mutually exclusive, so a control cannot be
  * both valid AND invalid or invalid AND disabled.
  */
public readonly status!: string;

Answer №2

Could you please create a StackBlitz example to clarify your intentions?

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

What is the correct way to invoke a function with a string contained within an object?

Looking for a way to call a function from an object using a string. Here's an example scenario: type = 'human' json: { action: 'run', type: this.type, //<- Need to call the function associated with the variable type ...

Ways to optimize image focus on a webpage

Upon loading the page, I desire for my image to be automatically focused. Unfortunately, setting the tabindex parameter has not produced the desired outcome. This is likely due to the fact that there are multiple angular2 header components with defined t ...

Accessing and transferring files through Angular with a .NET Core API

I am working on an Angular application that utilizes a .Net Core API to handle image uploads and retrieval. Here is the code for my Angular service: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angul ...

Operate Angular 4 and Node API simultaneously

As a newcomer to Angular, I am tasked with developing a web application using Angular4 for the front end and REST API with Node.js for backend connectivity with Ms SQL. I find myself questioning whether it's better to develop both projects separately ...

Converting a string representing time to a date object in Angular

Converting a string representation of time to a Date object var timeString = "09:56 AM"; this.audit_time = new Date(timeString); // Error: Invalid date I'm facing an issue with this conversion. Any suggestions on how to correct it? Please help me s ...

When grouping an array of objects by their property, the error "object index does not have an explicit type" may be encountered

My task involves dealing with an array of objects called Product. The structure of the Product class is as follows: class Product { id: string; type: string; price: number; constructor(id: string, type: string, price: number) { thi ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

Intellisense in VS Code is failing to provide assistance for data within Vue single file components

I am working with a simple code snippet like this https://i.sstatic.net/JSEWJ.png However, within the method, the variable 'name' is being recognized as type any. Interestingly, when I hover over 'name' in the data, it shows up as a s ...

Unleashing the Power of Angular16 and MongoDB with Multiple Parameters in Http

I am facing an issue where I need to pass two parameters to my endpoint, which adds up to three parameters in total. However, my HTTP POST request only allows two parameters. I have tried using HttpParams but it did not work in this scenario. The specific ...

What is the best way to reassign key-value pairs in JSON mapping using JavaScript/TypeScript?

Given {"a": {"name": "king", "firstname": "Thomas"},"b": {"age": "21"}} I'm exploring a simple way to convert it to {"name": "king","firstname": "Thomas","age": "21"} In the realm of Javascript/Angular. Any helpful suggestions are greatly appreci ...

Tips for retrieving only the changes or updates from DynamoDB streams

Currently, I am faced with a scenario where I must comprehend the distinction between NEW_IMAGE and OLD_IMAGE on dynamoDB streams. As per the information available at: https://aws.amazon.com/blogs/database/dynamodb-streams-use-cases-and-design-patterns/ ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

I noticed an excess of white space on the right side of my Angular website

Check out my website here. Everything seems to be functioning correctly, however, there is an issue with scrolling on mobile. It should only scroll up and down, not left and right! I have noticed a strange white space on the right side of my site when view ...

React Redux: Discrepancy in Variable Value Between Internal and External Function within Custom Hook

Encountering a challenge with a custom React hook utilizing Redux, where a variable's value inside and outside a function within the same hook is inconsistent. Simplified code snippet provided below: import { useAppSelector } from "Redux/helpers& ...

Using the expect statement within a Protractor if-else block

My script involves an if-else condition to compare expected and actual values. If they do not match, it should go to the else block and print "StepFailed". However, it always executes the if block and the output is "step passed" even when expected does not ...

Setting up an Angular CLI project

In our Angular 2 application, we utilize native CSS components that contain some JavaScript files. These components have wrappers to convert them into Angular 2 components. Now, I am looking to create a new Angular 4 project using Angular CLI and incorpora ...

Is it feasible to make a <mat-form-field> unfocusable?

Within my form field setup, a simple form field is presented: <mat-form-field> <mat-label>A label</mat-label> <input matInput type="text"/> </mat-form-field> By default, clicking on any part of the form field tr ...

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

Using the Angular Slice Pipe to Show Line Breaks or Any Custom Delimiter

Is there a way in Angular Slice Pipe to display a new line or any other delimited separator instead of commas when separating an array like 'Michelle', 'Joe', 'Alex'? Can you choose the separator such as NewLine, / , ; etc? ...

How to style a parent div with a background class in Angular 6

In my Bootstrap 4 project, I am creating an accordion that consists of cards. Each card contains various icons such as edit, view, and details. When any of these icons are clicked, a function in the component is triggered to navigate the user to a child ro ...