'Angular. Form Model Validation

I'm trying to follow an example from Adam Freeman's book on Angular and now stuck with Using a Form Model for Validation.

I have a similar issue as in Angular Typescript FormGroup assigning value after submit.

However, the accepted answer in that post didn't actually help me, because I got another error message: "Type 'any' is not assignable to type 'never'.ts(2322)".

So, I have an object of class Product:

export class Product {
    constructor(public id?: number,
    public name?: string,
    public category?: string,
    public price?: number) {}
}

In the form class I'm trying to do the following: enter image description here

Why does TS state: this.newProduct[c] is of type 'never'? And how do I make it work?



Solution 1:[1]

Why are you looking for the values looping over the controls?

You should be able to just do this:

const newProduct = formGroup.value

If not, either you built up your form wrong, or your model isn't right.

But if you can loop over the keys and assign them to your newProduct class member (which you do not need) it looks to me like just assigning the forms value property should work fine. I think you're over complicating things.

By not having the newProduct class member you do not need to concern yourself with creating a new Product after you submit the form. That is what the reset on the formgroup is for.

Why you are flipping a boolean 'formSubmitted' is also unclear to me, when you set it to true, you are actually not sure if you actually did submit it. You can't be sure until you make the actual call. And u immediately set it to false again, even when the call were to fail.

Solution 2:[2]

this.newProduct[c] makes no sense to me, what exactly are you trying to achieve here? Product is a class and you're using it like an array, hence it being of type never.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tu Nguyen