У меня есть этот код в моем component.ts, который заполняет форму данными пользователя, который получает идентификатор в качестве параметра
export class EditComponent implements OnInit {
async ngOnInit() {
await this.makeForm(this.user);
this.activatedRoute.params.subscribe(
params => this.userService.getUser(params.id).subscribe(
resp => this.user = resp
)
);
}
async getUserId(id: number) {
await this.userService.getUser(id).subscribe(
resp => {
this.user = resp;
this.formulario.controls.nombre.setValue(this.user['nombre'])
console.log(this.formulario)
},
err => console.log(err)
);
}
makeForm(user) {
console.log(user);
this.formulario = this.formBuilder.group({
name: ['', Validators.required],
lastname: ['', Validators.required],
country: ['', Validators.required],
city: ['', Validators.required]
});
}
ngDoCheck () {
if (this.user && this.formulario) {
// tslint:disable: no-string-literal
this.formulario.controls.name.setValue(this.user['nombre'].toString());
this.formulario.controls.lastname.setValue(this.user['apellidos'].toString());
this.formulario.controls.country.setValue(this.user['pais'].toString());
this.formulario.controls.city.setValue(this.user['ciudad'].toString());
}
}
updateUser() {
this.submitted = true;
console.log(this.formulario);
if (this.formulario.invalid) {
return;
}
const data = {
id: this.user['id'],
nombre: this.formulario.value.name,
apellidos: this.formulario.value.lastname,
fechaNacimiento: date,
pais: this.formulario.value.country,
ciudad: this.formulario.value.city
};
this.userService.updateUser(data).subscribe(
resp => this.router.navigate(['']),
err => console.log(err)
);
}
}
И это код html для ввода
form [formGroup]="formulario" class="form">
<table cellspacing="0">
<tr>
<td>
<mat-form-field>
<input
matInput
value="{{ user.nombre }}"
formControlName="name"
class="full-width"
/>
</mat-form-field>
</td>
</tr>
Проблема в том, что входные данные остаются с пользовательской информацией, и они не могут быть изменены, вы не можете записывать в них и не удалять, они остаются только stati c, и я не знаю, что возможно. Если я не заполняю форму, то при отправке ее появляются пустые значения.