0

I am trying to put form validation but I am getting form element is undefined. If I remove app-root element from index.html, it starts working as per expectation.

<!doctype html>
<html lang="en" ng-app>
<head>
    <meta charset="utf-8">
    <title>NKZ Technologies</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="script" src="../node_modules/angular/angular.min.js"> 
    </script>
    </head>
    <body>
        <form name="myForm">
          Valid = {{myForm.$valid}}
        ̶<̶/̶f̶o̶r̶m̶>̶
         <app-root></app-root>
        </form>
    </body>
</html>

Thanks, Ankit


@georgeawg your suggestion works for me but only in index.html.

Now app-root element renders app.component. I am having same form undefine issue in app.component.html.

<div id="main-content">
  <form name="test">
      a = {{test.$valid}} 
  </form> 
</div> 
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Ankit Rajpoot
  • 87
  • 1
  • 3
  • 12

2 Answers2

0

Include the <app-root> component in the <form> element:

<body>
  <form name="myForm">
    Valid = {{myForm.$valid}}
  ̶<̶/̶f̶o̶r̶m̶>̶
    <app-root></app-root>
  </form>
</body>

The input elements inside the <app-root> component can only register with the form controller if it encloses those elements.


Also, remember to import the FormsModule:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent],
  imports: [
    CoreModule,
    FormsModule
  ],
})
export class AppModule {}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • I am using angular 2. your suggestion works for me but only in index.html. Now app-root element renders app.component. I am having same form undefine issue in app.component.html.
    a = {{test.$valid}}
    – Ankit Rajpoot Jun 24 '18 at 22:19
  • Possible duplicate of [Angular 2 nested forms with child components and validation](https://stackoverflow.com/questions/44408188/angular-2-nested-forms-with-child-components-and-validation) – georgeawg Jun 24 '18 at 23:13
0

Resolved. Below trick wors for me.

<form (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>  

Thanks,

Ankit Rajpoot
  • 87
  • 1
  • 3
  • 12