Issue
I need your help. I have a small piece of code with which I want to send my fields to the backend. There are no errors in the code, I get the object in the database, but after sending the form, I get the following error:
TypeError: this.form.get is not a function
.
What i am doing wrong, where is my mistake? Thank you very much
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {UserService} from "../services/user.service";
@Component({
selector: 'app-users-table',
templateUrl: './users-table.component.html',
styleUrls: ['./users-table.component.css']
})
export class UsersTableComponent implements OnInit{
usersFormGroup: FormGroup;
constructor(
private userService: UserService,
private formBuilder: FormBuilder) {}
ngOnInit() {
this.usersFormGroup = this.formBuilder.group({
username: '',
name: '',
surname: '',
email: '',
password: '',
})
}
saveUserToDataBase() {
const newUser = this.usersFormGroup.value;
this.userService.createUser(newUser).subscribe(value => this.usersFormGroup = value);
}
}
Template
<form [formGroup]="usersFormGroup">
<input type="text" formControlName="username">
<input type="text" formControlName="name">
<input type="text" formControlName="surname">
<input type="email" formControlName="email">
<input type="password" formControlName="password">
<button (click)="saveUserToDataBase()">Створити</button>
</form>
Solution
you are wrong in this line
this.userService.createUser(newUser).subscribe(value => this.usersFormGroup = value);
usersFormGroup
is a FormGroup instance, not a user object. So, you need to use setValue
or patchValue
to set the new value to the form. I suggest you should use patchValue
because it is the best way to modify the form value when you don't know the user object has enough properties, it can update the form value based on the key of that object that existed in the form
this.userService.createUser(newUser).subscribe(value => this.usersFormGroup.patchValue(value));
Answered By - Anh Le
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.