Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formControlName must be used with a parent formGroup directive

While creating model driven form, i am getting an error: Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

Please tell me whats going wrong in this code.

app.component.html

<div class="col-md-6">
  <form  (ngSubmit)="saveSession(newSessionForm.value)" autocomplete="off">
    <div class="form-group">
      <label for="sessionName">Session Name:</label>
      <input formControlName="name" id="sessionName" type="text" class="form-control" placeholder="session name..." />
    </div>
    <div class="form-group">
      <label for="abstract">Abstract:</label>
      <textarea formControlName="abstract" id="abstract" rows=3 class="form-control" placeholder="abstract..."></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
  </form>
</div>

app.component.ts

export class CreateSession {

    newSessionForm:FormGroup;
    abstract : FormControl;
    name : FormControl;

    ngOInInit(){
        this.name = new FormControl('', Validators.required)
        this.abstract = new FormControl('', Validators.required)

        this.newSessionForm = new FormGroup({
            name:this.name,
            abstract: this.abstract
        })         
    }


    saveSession(formValues){
        console.log(formValues);
    }
like image 214
Er Vipin Sharma Avatar asked Aug 22 '17 15:08

Er Vipin Sharma


1 Answers

Angular is waiting for FormGroupDirective on any of parent elements. So:

<form [formGroup]="newSessionForm" ...
  <input formControlName="name"
  ...
  <input formControlName="abstract"

If you want to use FormControl without formGroup you can use FormControlDirective instead:

<input [formControl]="name"
...
<input [formControl]="abstract"
like image 82
yurzui Avatar answered Sep 22 '22 03:09

yurzui