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

Implementing Azure AD authentication with Angular and .NET Core 2 Web API

My goal is to implement authentication in my application using Azure AD Currently, the flow of my application looks like this: User -> AngularApp -> Azure Login -> AngularApp with token -> API Call to backend with token -> Backend verifies token with Azu ...

Encountering a Typings Install Error When Setting Up angular2-localstorage in WebStorm

I am currently using Windows and WebStorm as my development environment. I attempted to install the angular2-localstorage package by running the command npm install angular2-localstorage, but encountered an error. After realizing that the angular2-localst ...

The confirmPasswordReset function in Angularfire auth is not defined in the User type

I am currently working on integrating password reset functionality using the angularfire2/auth class, following the steps outlined in this guide: https://medium.com/@c_innovative/implementing-password-reset-can-be-a-tricky-but-inevitable-task-737badfb7bab ...

I find it confusing how certain styles are applied, while others are not

Working on my portfolio website and almost done, but running into issues with Tailwind CSS. Applied styling works mostly, but some disappear at certain breakpoints without explanation. It's mainly affecting overflow effects, hover states, and list sty ...

Alternative to bower_concat for NPM

bower_concat is an amazing tool. Simply add a bower package using: bower install something --save Then bower_concat will gather the javascript and CSS from that package and combine it into a bundle, resulting in vendor.js and vendor.css files that can be ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

Dynamic controller in TypeScript with React Hook Form

Is there a way to ensure that the fieldName is always inside the control? Passing a field name that doesn't exist in the form causes issues for me, so I'm looking for a solution. Can anyone help? import { Control, Controller } from 'react-ho ...

Setting a global property within the complete method of an ngrx Angular subscriber is a helpful technique to ensure that

Currently, I have a global property called loadingIndicatorsearchVisible = false;. In addition, there is a method containing an observable, where I manipulate the loadingIndicatorsearchVisible to display or hide a loading panel. search(){ this.loadingI ...

The issue with APP_INITIALIZER is that it fails to resolve promises before moving on to other

I can't seem to figure out what's missing here. I hope it's just a minor issue. The problem I'm facing is that the APP_INITIALIZER isn't resolving completely. In my code, I have two services: AppSettingsService and SomethingServi ...

Finding the Height of a Document in Angular 2

I'm currently in the process of transitioning some jQuery code to Angular 2, and am facing difficulties in finding a way to retrieve the height of the document. The jQuery code I've been using is $(document).height(); Could you please provide ...

What could be causing the table to display empty when we are passing data to the usetable function?

Visit Codesandbox to view Table While the header appears correctly, I noticed something strange. When I console log the data props, it shows all the necessary data. However, when I try to console.log row, there doesn't seem to be any single object re ...

Updating the reference path in the index.html file during Angular 6 build process

When developing an Angular 6 application, the scripts and CSS files are automatically generated with hashed values at the end of their names. I am wondering if it is possible to update the links to these files in the index.html file. Currently, they point ...

The jsPDF html() method is incorrectly splitting the HTML element

I have been working on creating an invoice report using jsPDF in an Angular 7 app. The report is text-based as images are not accepted by the client. In my code, I have a main div with the id "report" which I retrieve and pass to the .html() function. With ...

Issue: fs.js:47 } = primordials; ^ ReferenceError: primordials is not defined - Please handle this error

I encountered an issue where my node version is 12.11.1, however when I try running the command npm run server, it returns an error message as displayed below: fs.js:47 } = primordials; ^ ReferenceError: primordials is not defined at fs.js:47:5 ...

Discuss the communication paths between Server and Client components in the upcoming 14 days

Currently, my objective is to transfer state from a client component to a server component, perform some actions on the server, and then send the updated state back to the client through props. I am in the process of building a booking system using tools ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

Encountering an error in resolving symbol values statically within the Angular module

Following a helpful guide, I have created the module below: @NgModule({ // ... }) export class MatchMediaModule { private static forRootHasAlreadyBeenCalled: boolean = false; // This method ensures that the providers of the feature module ar ...

Issue with nestjs build due to ts-loader module in dev-dependency

I've encountered a Module Error with ts-loader during a docker build ERROR [6/6] RUN nest build 3.9s ------ > [6/6] RUN ...

Creating custom components in AngularJS 2 allows you to define methods unique to each component. Want to learn

I created my component (A) by combining multiple html elements, but I have two questions. How do I define methods (such as get, etc.) on my component? I have tried @Output, @ViewChild, etc. but they are not working. I am looking for an alternative way ...