I need to fill in the form with the user data to be able to edit them, but I don't know how to do it.
This is the form.
this.formEditarUser = this._builder.group({
name: ['', Validators.required],
cpostal: ['', Validators.required],
provincia: ['', Validators.required],
localidad: ['', Validators.required],
pais: ['', Validators.required],
surname: ['', Validators.required],
imagen: [''],
});
I tried to put it in the function that brings me the user data, but it gives an error, and I try to fill it with a separate function but it doesn't fill it either.
rellenarFormuluario() {
this.formEditarUser.value.name.setValue(this.nombre);
}
It only displays on the form if I do it directly in the constructor.
Here I assign the name to the variable
getUserEditar() {
this._serviceUser.edit(this.idUserConectado).subscribe(
response => {
this.user = response;
this.nombre = response.name;
this.rellenarFormuluario();
console.log(this.formEditarUser.value.name);
}
);
}
To fill in the fields of a reactive form angular provides you with two methods
patchValue
andsetValue
. Here the documentation.patchValue updates all the fields it finds in the model you pass to it as a parameter. If it doesn't find a field, it doesn't throw any error.
setValue is stricter when it comes to updating the values, that is, it validates that the model has the same structure and properties as the form fields. If any are missing, it throws an error.
Imagine that in your case you want to update only the fields
name
andcpostal
.If you use patchValue the update will not give you an error.
But with setValue it will give you an error because you need to pass the fields that are not updated.
To update all form fields
Update individual field