Issue with Angular reactive forms when assigning values to the form inputs, causing type mismatch

I'm a beginner when it comes to reactive forms. I'm currently working on assigning form values (which are all string inputs) from my reactive form to a variable that is an object of strings. However, I am encountering the following error:

"Type 'Partial<{ taskName: string | null; taskDate: string | null; taskPriority: string | null; }>' is not assignable to type 'ToDoDetailType'. Types of property 'taskName' are incompatible. Type 'string | null | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'."

export class ToDoMakerComponent implements OnInit{
    ngOnInit(): void {
        
    }
    toDoForm = new FormGroup({
        taskName : new FormControl<string>('',[Validators.required]),
        taskDate : new FormControl('',[Validators.required]),
        taskPriority : new FormControl('',[Validators.required])
    })
    toDoDetail:ToDoDetailType | undefined;
    onSubmit(){
        console.log(this.toDoForm.value);
        this.toDoDetail =  this.toDoForm.value //error raising line
    }

}
export interface ToDoDetailType{
    taskName: string,
    taskDate: string,
    taskPriority: string
}

Answer №1

You are facing 2 issues here :

  • FormControl automatically creates a nullable control, but it is not possible to create a nonNullable control with a validator. A common workaround is to use FormBuilder.nonNullable.
  • todoForm.value returns a Partial<ToDoDetailType > because any disabled FormControl will not be included in the value. If you are certain that no controls will be disabled, an alternative method is getRawValue().

This results in :

constructor(private fb:FormBuilder) {}
  
toDoForm = this.fb.nonNullable.group({ // create a non nullable group
taskName: ['',  [Validators.required]],
taskDate: ['', [Validators.required]],
taskPriority: ['', [Validators.required]],
});

onSubmit() {
this.toDoDetail = this.toDoForm.getRawValue(); // Not a partial
}

Answer №2

Another way to approach it is:

storeTaskDetails =  {
    name: formValues.name,
    date: formValues.date,
    priority: formValues.priority
} 

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

Removing an object from an array when a certain key value already exists in TypeScript

I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have: ...

Is it possible to pass a different variable during the mouse down event when using Konva for 2D drawing?

I am trying to pass an additional value in a mouse event because my handleMouseDown function is located in another file. stage.on('mousedown', handleMouseDown(evt, stage)) Unfortunately, I encountered an error: - Argument of type 'void&apos ...

Back up your Firestore data automatically using scheduled cron jobs!

Recently, I utilized the firestore-backup-restore tool for backing up Firestore data and it worked seamlessly. However, I am unsure how to schedule this process using cron jobs or a similar method. As someone with no prior experience in utilizing cron jobs ...

Does an AsyncMethod().Result equivalent exist in typescript?

When working in C#, you have the ability to call the result of an asynchronous method synchronously by accessing the Result property. For example: var returnVal = AsyncMethod().Result; What is a similar approach in typescript? ...

Is it possible to navigate to the Angular component that defines a tag in VSCode by simply clicking on the tag?

In my current Angular project in VSCode, I often find myself wanting to delve deeper into specific tags that I encounter while coding. For instance, if I stumble upon a tag like <display-active-users>, I usually have to go through the process of sea ...

Setting up domain or IP Address in Angular with Spring Boot: A step-by-step guide

I'm facing an issue with my Angular 11 application hosted in the public folder of a Spring project. The Spring project is running on port 8075, and when I access my application from localhost:8075, everything works perfectly fine. However, when I try ...

Accessing the personal data fields of a MongoDB object

My current environment setup includes: NodeJS: 5.7.1 Mongo DB: 3.2.3 MongoDB (NodeJS Driver): 2.1.18 TypeScript: 1.8 I have defined an Object using Typescript as: class User { private _name:string; private _email:string; public get name():strin ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

The rendering of code is often disrupted when utilizing the keyword const

I've been working my way through the Angular2 tutorial called Tour of Heroes and everything has been going smoothly up until this point. At the link above, I've encountered a problem. The code on the left is what the tutorial recommends, but fo ...

Creating an Angular Confirm feature using the craftpip library

Trying to utilize the angular-confirm library, but finding its documentation unclear. Implementing it as shown below: Library - In button click (login.component.ts), ButtonOnClickHandler() { angular.module('myApp', ['cp.ngConfirm']) ...

Tips for cycling through the backend API map reaction in Angular or Typescript

When I make a call to an API, it returns a response in the form of a map: {thomas: 3, test70: 2, tim: 2, elin: 2, sumeet12: 1} I tried iterating over this response in Angular, but encountered an error. Error Encountered: This expression is not callab ...

Having difficulty retrieving values while using async-await

Utilizing the code below has been successful for me. I managed to retrieve the data in the spread (then), returning a http200 response. Promise.all([ axios({ method: 'post', url: 'https://oauth2.-arch.mand.com/oauth2/token&a ...

The command "ng test" threw an error due to an unexpected token 'const' being encountered

Any assistance with this matter would be greatly appreciated. I am in the process of constructing an Angular 5 project using angular/cli. The majority of the project has been built without any issues regarding the build or serve commands. However, when a ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

Ways to define an interface that can accommodate various interfaces with a specific structure

I am in need of a function that can accept a parameter with interfaces having a specific structure. The parameter should be either a string hash or a string hash along with an attribute string hash, as shown below: { anotherHash: { a: 'a', ...

What is the process for implementing a type hint for a custom Chai assertion?

As part of my typescript project, I decided to create a custom assertion for the chai assertion library. Here is how I implemented it: // ./tests/assertions/assertTimestamp.ts import moment = require("moment"); import {Moment} from "moment"; const {Asser ...

Even when imperfections inevitably arise, flawless submission is always achieved

When working with a form that has a set minimum and maximum number of characters, I encounter an issue. If the minimum is set to 2 characters and I only input one character, I receive a mat-error message. However, upon clicking save, it allows me to procee ...

Issues retrieving data using Ionic 4 native HTTP plugin result in returning an empty

Currently, I am working on an Ionic 4 project where I am attempting to retrieve a JSON array from a URL using the native HTTP for Ionic. However, when I attempt to fetch the data array from the URL in JSON format, I am met with an empty page. The JSON dat ...

Issue with using loadChildren in Angular 11 routing

Once I log in to my app, I navigate to the link: this.router.navigate(['/sellTicket/chooseTicket']); In my app-routing configuration, I have the following setup: const routes: Routes = [ {path: 'login', component: LoginComponent}, ...