Transforming Form Field Inputs into Model Data Types

Looking at my Angular 8 component, there is a form that allows users to create a post.

The PostModel consists of three properties: a string, a boolean, and a number:

export interface PostModel {
  title: string
  year: number;
  approved: Boolean;  
}

The issue arises when I try to create a PostModel from the form values as everything ends up being treated as strings:

  let model: PostModel = { 
    title: this.form.value.title,
    approved: this.form.value.approved,
    year: this.form.value.year
  };

How can I correctly generate a PostModel from the form values while maintaining the correct property types?

Here's the code snippet for the component:

export class PostCreateComponent extends Modal implements OnInit {

  form: FormGroup;

  constructor(private formBuilder: FormBuilder, private postService: PostService) { }

  ngOnInit() {

    this.form = this.formBuilder.group({  
      title: [''],
      year: [''],
      approved: ['']
    });

  }

onSubmit() {

  if (this.form.valid) {

    let model: PostModel = { 
      title: this.form.value.title,
      approved: this.form.value.approved,
      year: this.form.value.year
    };

    // Implement logic to create the post

  }

}

Answer №1

  1. Have you tried using type="number" in your HTML code?
  2. If that didn't work, I suggest converting it to a number with the following step
value: number = +year;
// The + symbol is used for converting a string to a number

Answer №2

Unfortunately, the FormControl value type is limited to just any. However, one possible workaround is to create a new class that extends this one and adds the necessary type restriction:

class TypedFormControl<T> extends FormControl {
    get value(): T | null {
        return super.value;
    }

    get valueChanges(): Observable<T | null> {
        return super.valueChanges;
    }
}

export class PostCreateComponent {
    readonly yearControl = new TypedFormControl<number>();
    readonly form = new FormGroup({
        year: this.yearControl,
        ...
    })

    ...

    onSubmit() {
        ...
        const post: PostModel = {
            year: this.yearControl.value,
            ...
        }
    }
}

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

Accessing Nested FormGroup in Angular 6 by its name

Dealing with Nested Form Groups address = new FormGroup({ 'com.complex.Address':new FormGroup({ city: cityControl, streetName: streetNameControl, houseNumberAddition: houseNumberAdditionControl, ho ...

Adding local images to Excel can be easily accomplished using Office Scripts

Hello, I've been attempting to replace Excel cells that contain image filepaths with the actual images themselves. I found an example in Office Scripts that shows how to insert images with online URLs but doesn't mention anything about inserting ...

Injecting dynamic templates in Angular 7

Let me simplify my issue: I am currently using NgxDatatable to display a CRUD table. I have a base component named CrudComponent, which manages all CRUD operations. This component was designed to be extended for all basic entities. The challenge I am en ...

Execute an npm script using a gulp task

Is there a way to execute an npm script command within a gulp task? package.json "scripts": { "tsc": "tsc -w" } gulpfile.js gulp.task('compile:app', function(){ return gulp.src('src/**/*.ts') .pipe(/*execute npm run tsc*/ ...

I've tried using a ControlValueAccessor, but for some reason the value isn't getting passed to the form

Currently, I am experimenting with reactive forms in Angular, and I'm encountering difficulties with updating the form from custom components. As an example, take a look at the date-input component created using flatpickr in the linked Plunker demo. ...

Angular removing every query string parameters

Linked to but distinct from: How to maintain query string parameters in URL when accessing a route of an Angular 2 app? I am facing an issue with my basic Angular application where adding a query parameter results in its removal, both from the browser&apo ...

Tips for simulating a "nested" angular service within a component using jest

I'm looking to create a unit test for an Angular Component using Jest. The component, which is built on Angular version 7.2.0, interacts with a nested service through this.api.manageUser.getUsersStats(). My goal is to verify if this method is being ca ...

My Angular custom libraries are having issues with the typing paths. Can anyone help me troubleshoot what I might be doing

After successfully creating my first custom Angular library using ng-packagr, I encountered an issue where the built library contained relative paths specific to my local machine. This posed a problem as these paths would not work for anyone else trying to ...

I require the ability to identify and capture the ID of the button (touchable opacity) that has been

When trying to delete a selected button by obtaining its specific id, I am facing an issue where after the first execution, the id of the deleted item is retained instead of the newly selected one. I am in need of a solution that allows me to retrieve the ...

Trouble occurs in the HTML code when trying to access a property from an inherited interface in Angular

Currently, I am working with Angular 17 and have encountered a specific query: In my project, there is an IDetails interface containing certain properties: export interface IDetails { summary: Summary; description: string; } Additionally, there is an ...

When RxJS returns an empty observable, it does not trigger the successful action

I am working with a Rxjs effect that has the following structure: callApiPostSyncPushEffect$ = createEffect(() => { return this.actions$ .pipe( ofType(SyncActions.callApiPostSyncPushPullAction), mergeMap((action) ...

What causes the variation in typing behavior between specifying props directly on a component versus nesting them inside another prop?

Understanding the next component might be a bit tricky, so let's delve into it (Check playground): type Props<T> = { initValue: T, process: (value: T) => T } export const Input = <T,>({ initValue, process, }: Props<T>): ...

Tips for utilizing the material ui auto-complete search feature

I am in search of an alternative to material-ui-search-bar because it is no longer being maintained. I have been suggested to try using Material UI's auto complete instead. However, from the examples I've seen, it seems like only text field struc ...

Issue with extending mongoose.Document properly in NodeJS and TypeScript using a custom interface with mongoose

I recently started learning Typescript and tried to follow this guide to help me along: After following the guide, I implemented the relevant code snippets as shown below: import { Document } from "mongoose"; import { IUser } from "../interfaces/user"; ...

Angular tutorial: Changing website language with translation features

Looking to translate my existing Russian website into another language using angular localization. Any recommendations on where I can find resources or tutorials for this? ...

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...

Which one should you choose for NodeJS: Promise or Callback?

When it comes to writing node functions, I have come across 2 different approaches - using promise or callback. The first method involves defining the findByEmail function as follows: class Users{ static async findByEmail(email: any ) : Promise<Users ...

What is the best way to obtain a reference to an instance of my Angular 2 directive?

Angular 2 rc 5 was written using typescript 1.9 I am trying to access the instance of my attribute directive. Although I am using ViewChild, which typically works with components, it is giving me a handle to the element containing the directive. template ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

Error code 1 in Ionic V5 Capacitor - cordova-plugin-media indicates a problem with media playback

Despite installing the plugin and ensuring all necessary permissions are set, I am still encountering error code 1 with the media plugin. I have also included <application android:requestLegacyExternalStorage="true" /> in <edit-config&g ...