FormGroup ERROR TypeError: Cannot read property 'get' of undefined

Gallo picture Gallo · Apr 23, 2018 · Viewed 43.8k times · Source

I am trying to get a value from my form and I am getting this error: ERROR TypeError: Cannot read property 'get' of undefined

 addMessage: FormGroup;
 get message(){ return this.addMessage.get('message').value}

Html:

 <form [formGroup]="addMessage" (ngSubmit)="sendMessage()">
      <input formControlName="message" class="input" type="text">
      <button type="submit" class="button is-primary">Send</button>
  </form>

Answer

Shoyeb Memon picture Shoyeb Memon · Apr 23, 2018

You did was everything right, but you need to build a FormBuilder too.

Kindly follow my method of getting data from a form.

html:

<form [formGroup]="WordpressForm">

 <div class="form-group">
   <mat-form-field class="example-full-width">
     <input matInput placeholder="Title" [(ngModel)]='title' formControlName='title'>
   </mat-form-field>
   <div>        
   <button (click)="save()">Save</button>
  </div>
 </div>
</form>

ts:

constructor(private fb: FormBuilder) {}

WordpressForm = this.fb.group({
  title: ['', [Validators.required]]
});

getTitle() {
 return this.WordpressForm.get('title');
}

save() {
 const template_Title = this.title;
 console.log(template_Title);
}