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>
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With