Home > Mobile >  Angular. Form Model Validation
Angular. Form Model Validation

Time:05-15

I'm trying to follow an example from Adam Freeman's book on Angular and now stuck with Using a Form Model for Validation. Originally, I've got a similar issue as in enter image description here

Can anyone explain me please, why TS states this.newProduct[c] is of type 'never'? How to make this code work? Please, any help!

CodePudding user response:

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.

CodePudding user response:

I think it is trying to assign the product property to the foreach return. Try wrapping your lambda function with curly braces.

keys.forEach(c => {
 this.newProduct[c] = this.formGroup.controls[c].value;
});

Apologies if this doesn't work, new here.

CodePudding user response:

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.

  • Related