FormGroup ERROR TypeError: Cannot read property 'get' of undefined
The approach I'd suggest is this:
First: Import the ReactiveFormsModule into the module that offers the component (the one you are importing the component that has the form into)
Second: Import FormGroup and FormBuilder into your form component
Third: declare the variable that will be your form name, as such:
public myFormName: FormGroup;
Pleace notice that I have given the variable the FormGroup type. At the template, you will assign the content of your form to this variable (make sure it is public, not private), like this:
<form [formGroup]="myFormName">
Forth: Declare, at the component's constructor, a private variable with the type "FormBuilder", as such:
constructor(private readonly formBuilder: FormBuilder)
Fifth: create a public method that will 'create' your reactive form, something like this:
createForm(): void {
this.form = this.formBuilder.group(
{
name: [''],
gender: [''],
birth_date: ['']
},
);
}
Make sure the property name maps a formControlName
in your template. Initialize each property with a ' ' value, or the initial value you want it to have (make sure it is of the same type declared on the template)
Last: Call the form creation method on the component's constructor, so the form will be instantiated when the template renders.
Bonus round: If your form is simple, consider using template driven forms. Reactive forms are more robust, and meant to be used when you need to have more control over your form.
Read more here: https://angular.io/guide/reactive-forms
Use this
return this.addMessage.controls['message'].value
For more information you can play here on official playground of form in angular
You can try this :
import { FormControl } from '@angular/forms';
...
addMessage = new FormGroup({
message: new FormControl()
});
get message(){
const messageControl = this.addMessage.controls['message'];
return messageControl.value;
}
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);
}