Form validation - property does not exist


#1

The following works in serve but not when building for android:

this.myForm = formBuilder.group({
  'name': ["", Validators.required]
  'slogan': "",
  'category': ["", Validators.required]
})

I have also tried:

    formInfo = {
name: '',
slogan: '',
category: ''

}
this.myForm = formBuilder.group({
‘name’: [this.formInfo.name, Validators.required]
‘slogan’: ‘’,
‘category’: [this.formInfo.category, Validators.required]
})

Errors for both are:
Property ‘name’ does not exist on type '{ key string] :AbstractControl
Property ‘category’ does not exist on type '{ key string] :AbstractControl

No error for slogan as is not required.

Do I need to use AbstractControl?


#2

The following syntax has worked for me:

this.myForm = formBuilder.group({
name: ["", Validators.required],
slogan: [""],
category: ["", Validators.required]
});

  • Removed quotes from name/slogan/category
  • added brackets for slogan’s empty string
  • added comma’s at the end of each line except the last

#3

Thanks njm250,

Other than the comma which was a slip up I must have made formatting in this forum, I can make what I originally posted by not referencing the control in the html.

eg: <p [hidden]="myForm.controls.name.valid" danger padding-left>Subject is empty</p> does not work when published to android.

But this works:

<p [hidden]="!isValid( 'name')" danger padding-left>Name is empty</p>

…when used with this function:

isValid(field: string) {
let formField = this.myForm.get(field);
return formField.valid || formField.pristine;

}

So it seems the myForm.controls.name.valid is the problem.

When you use your suggestion and utilize myForm.controls.name.valid in your html, can you build out Android?


#4

According to angular #10192, direct access to the controls array that way is not supported.


#5

That would explain it.
On a side note, it states to use this.myForm.find('myfield').valueChanges
I cannot use find so use get.

isValid(field: string) {
let formField = this.myForm.get(field);
return formField.valid || formField.pristine;

}


#6

get was added a bit later.


#7

Yup.
Unless there is a better suggestion, I will keep on with the isValid function.
Thanks to both of you.