Angular forms unable to see the template of few fields

Viewed 44

I have a sample project where I have used angular forms. I have created form group object and added form controls and all. But unable to see password field which is in the template and form is not working. Here is the code.

Stackbliz Link

app.component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public form: FormGroup = new FormGroup({
    email: new FormControl('', [Validators.required]),
    password: new FormControl('', [Validators.required])
  });

  login() {
    if (this.form.valid) {
      console.log(this.form.value);
    }
  }
}

app.component.html

<h3>Login Form</h3>
<form (ngSubmit)="login()">
  <label>Email: </label>
  <input formControlName="email" type="text" />
  <br><br>
  <label>Password: </label>
  <input  formControlName="password" type="password" />
  <br><br>
  <button type="submit">Login</button>
</form>
2 Answers

Add formGroup attribute in your form.

<form [formGroup]="form" (ngSubmit)="login()">...

There are two things you have missed in the code one is to add formGroup as said by ammad and also you have to add Reactive forms module in app.module.ts file.

Stackbliz Link

Related