how can i edit a form array - html

I have an application where I want to edit the information of a FormArray, but I input!
I can create data, but I cannot edit it.
I've already tried to create another matrix form, but it still doesn't have any connection form when trying to edit data that already exists within this one.
my typescript code:
ngOnInit(): void {
this.projectInfoService.retrieveById(+this.activatedRoute.snapshot.paramMap.get('id')!).subscribe({
next: project => {
console.log(project)
this.project = project
this.rgForm = this.fb.group({
id: [this.project.id],
name: [this.project.name, Validators.required],
team: [this.project.team,],
description: [this.project.description, Validators.required],
tasks: this.fb.array([])
})
},
error: err => console.log('Error:', err)
});
}
get name() {
return this.rgForm.get('name')
}
get description() {
return this.rgForm.get('description')
}
get team() {
return this.rgForm.get('team')
}
get tasks(): FormArray {
return <FormArray>this.rgForm.get('tasks');
}
my html code:
<ng-container formArrayName="tasks" *ngFor="let task of tasks.controls; let i=index">
<div [formGroupName]="i" class="d-flex justify-content-center aling-items-center my-2">
<div class="col-md-5">
<div class="form-floating">
<input type="text" formControlName="nameTask" [attr.id]="'task' + i" id="floatingInputGridT"
class="form-control" placeholder="Nome da tarefa" required>
<label [attr.for]="'task' + i" for="floatingInputGridT">Tarefa</label>
</div>
</div>
<div class="col-md-5">
<div class="form-floating">
<select class="form-select" formControlName="member" [attr.id]="'taskMember' + i">
<option *ngFor="let member of _members" [value]="member.nameMember">{{ member.nameMember }}</option>
</select>
<label [attr.for]="'taskMember' + i">Membro da task</label>
</div>
</div>
<div class="d-flex justify-content-center aling-items-center flex-column">
<div class="col-md-1">
<button type="button" class="btn btn-danger" (click)="deleteTask(i)"><i
class="fa-solid fa-trash-can"></i></button>
</div>
</div>
</div>
</ng-container>
How can I edit the values ​​contained in this FomrArray?

Related

How to display error for field that haven't been "touched" on submit

I've an angular login, with reactive form:
public form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
name: ['', [Validators.required]],
});
When I click on submit, I do the following:
async createUser() {
if (this.form.valid) {
this.uiService.startBusyIndicator('Adding user...');
try {
await this.userSettingsService.createUser(this.form.get('name')?.value, this.form.get('email')?.value);
this.messageService.add({ severity: 'success', summary: 'User added', detail: 'User added successfully' });
} finally {
this.uiService.stopBusyIndicator();
this.form.reset();
}
} else {
console.log('Marking everything as touched');
this.form.markAllAsTouched();
}
}
Here is my form:
<p-dialog header="Add user" [(visible)]="displayAddForm" [modal]="true">
<form [formGroup]="form" (ngSubmit)="createUser()">
<div class="grid formgrid p-fluid">
<div class="field mb-4 col-12">
<label [for]="name" class="font-medium text-900"> {{ 'account.fields.name' | translate }}</label>
<input required pInputText formControlName="name" #name />
<app-field-errors
[formField]="form.controls['name']"
[fieldName]="'account.fields.name' | translate"></app-field-errors>
</div>
<div class="field mb-4 col-12">
<label [for]="email">{{ 'account.fields.email' | translate }}</label>
<input required pInputText formControlName="email" #email />
<app-field-errors
[formField]="form.controls['email']"
[fieldName]="'account.fields.email' | translate"></app-field-errors>
</div>
</div>
<div class="grid">
<button pButton type="submit" class="col-6 col-offset-6">Add user</button>
</div>
</form>
</p-dialog>
When I click on submit with having nothing as input, nothing changes, my fields still have the ng-pristine and not the ng-dirty classes?
I also tried to call this.form.markAsDirty(); but same result.
While testing I found that if I type some letters and remove them from input fields, they do get highlighted in red, which led to me to the realization that required validator doesn't effect the input fields, if you don't mark them as dirty, when they are in pristine state.
So, if you mark them accordingly, it should work for you, as you can see in this simplified Stacblitz example
component.ts:
form: FormGroup;
displayAddForm = true;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
name: ['', [Validators.required]]
});
}
async createUser() {
if (this.form.valid) {
alert('valid form');
} else {
console.log('Marking everything as touched');
this.form.markAllAsTouched();
for (const key of Object.keys(this.form.controls)) {
if(this.form.controls[key].value.length === 0) {
console.log('blank value');
this.form.controls[key].markAsDirty();
}
}
}
}
component.html:
<p-dialog header="Add User" [(visible)]="displayAddForm" [modal]="true">
<form [formGroup]="form" (ngSubmit)="createUser()">
<div class="grid formgrid p-fluid">
<div class="field mb-4 col-12">
<label [for]="name" class="font-medium text-900"> Name</label>
<input required pInputText formControlName="name" #name />
<div class="error"
*ngIf="form.controls['name'].touched && form.controls['name'].invalid">Name required</div>
</div>
<div class="field mb-4 col-12">
<label [for]="email">Email</label>
<input required pInputText formControlName="email" #email />
<div class="error"
*ngIf="form.controls['email'].touched && form.controls['email'].invalid">Email required</div>
</div>
</div>
<div class="grid">
<button pButton type="submit" class="col-6 col-offset-6">Add user</button>
</div>
</form>
</p-dialog>
Result (after clicking Add User, without touching any of the input fields):

Angular validations showing during the page load

We are working on the Angular 4 form and set some validations on the input field but the validation is showing when the page load's but we want the validation when the form is submitted or the field is not valid or filled.
Component.html
<div class="headerbutton-group row">
<i class="fa fa-save header-buttons" tooltip ="Save" tabindex="1" (click)="onSave($event)"></i>
<i class="fa fa-close header-buttons" tooltip ="Close" (click)="onCancel($event)"></i>
</div>
<form [formGroup]="editForm" class="col-md-12 ">
<div class="form-group row">
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Name</label>
<div class="col-md-12">
<input type="text" id="txtName" name="txtName" class="form-control" placeholder="Name" formControlName="name" [class.is-invalid]="!editForm.controls.name.valid" [class.is-valid]="editForm.controls.name.valid" required>
<div class="invalid-feedback" [style.visibility]=
"editForm.controls.name.valid ? 'hidden':'visible'"> Name is required</div>
</div>
</div>
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Description</label>
<div class="col-md-12">
<input type="text" id="txtDescription" name="txtDescription" class="form-control"
placeholder="Description" formControlName="description">
</div>
</div>
</div>
</form>
Component.ts
#Component({
selector: 'app-edit-form',
templateUrl: './component.html'
})
export class LoginFormComponent implements OnInit {
constructor(fb:FormBuilder) {
public editForm: FormGroup = new FormGroup({
name : new FormControl('', Validators.required),
description : new FormControl(''),
});
}
public onSave(e): void {
if (this.editForm.valid) {
e.preventDefault();
this.save.emit(this.editForm.value);
} else {
this.validateAllFormFields(this.editForm);
}
}
public onCancel(e): void {
e.preventDefault();
this.closeForm();
}
private validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
}
// Tried this too editForm.controls.name.pristine
We don't know what we are missing. Kindly help us, with useful documents/ Demo's.
try changing this
<div class="invalid-feedback" [style.visibility]="editForm.controls.name.valid ? 'hidden':'visible'">
Name is required
</div>
to this
<div class="invalid-feedback" *ngIf="!editForm.controls.name.valid && editForm.controls.name.touched">
Name is required
</div>
adding a test on "touched" will fix your problem !

Get a id from the formbuilder to delete a row in Angular 6

I have a HTML page with a few forms to fill in for the user:
<div class="card-body">
<form [formGroup]="FormCar" (ngSubmit)="AddCar(FormCar.value)">
<input type="hidden" formControlName="CarId" id="carId" />
<div class="row">
<div class="form-group col-sm-3">
<label>Brand</label>
<input type="text" class="form-control" formControlName="Brand" id="brand" placeholder="Enter brand">
</div>
</div>
<div class="row">
<div class="form-group col-sm-3">
<label>Model</label>
<input type="text" class="form-control" formControlName="Model" id="model" placeholder="Enter model">
</div>
</div>
<div class="row">
<div class="form-group col-sm-3">
<label>Color</label>
<input type="text" class="form-control" formControlName="Color" id="color" placeholder="Enter color">
</div>
</div>
<div class="row">
<div class="form-group col-sm-3">
<label>Speed</label>
<input type="number" class="form-control" formControlName="TopSpeed" id="topSpeed" placeholder="Enter speed">
</div>
</div>
<div class="btn-group mr-2">
<button type="submit" class="btn btn-danger mr-1">Save changes</button>
<button type="reset" class="btn btn-danger mr-1">New record</button>
<button type="button" class="btn btn-danger mr-1" (click)="DeleteCar(CarId)">Delete</button>
</div>
</form>
</div>
I use a HTML table to display data and when the user clicks on a row it fill with the inputs information. I used this method to fill the fields:
EditCar(carId: number) {
this.carservice.getCarById(carId).subscribe((res: any) => {
this.FormCar.patchValue({
CarId: res.carId,
Brand: res.brand,
Model: res.model,
Color: res.color,
TopSpeed: res.topSpeed
})
});
}
This is working good I have build my form with formbuilder like this:
buildFormCar() {
this.FormCar = this.formBuilder.group({
CarId: ['', Validators.required],
Brand: ['', Validators.required],
Model: ['', Validators.required],
Color: ['', Validators.required],
TopSpeed: ['', Validators.required],
});
}
After the fields are filled I want to delete it by his id and I use this method for it:
DeleteCar(carId: string) {
if (confirm("Weet u zeker?")) {
this.carservice.deleteCar(carId).subscribe(() => {
this.GetCar();
this.GetCarCount();
})
}
}
When I click on the delete button I get a error on the backend (I use .NET core)
This is the error message:
System.InvalidOperationException: 'The property 'CarId' on entity type
'Car' has a temporary value while attempting to change the entity's
state to 'Deleted'. Either set a permanent value explicitly or ensure
that the database is configured to generate values for this property.'
The method that I use in the backend look like this:
[Route("DeleteCar")]
[HttpDelete]
public IActionResult Delete(long id)
{
_context.Cars.Remove(new Car() { CarId = id });
_context.SaveChanges();
return Ok();
}
It seems it cannot find the carId when the delete happens.
Can someone point me in the right direction?
Try FormCar.get("CarId").value like this:
<button type="button" class="btn btn-danger mr-1" (click)="DeleteCar(FormCar.get("CarId").value)">Delete</button>
or Donot pass any parameter in DeleteCar() and do this:
DeleteCar() {
if (confirm("Weet u zeker?")) {
this.carservice.deleteCar(this.FormCar.get("CarId").value).subscribe(() => {
this.GetCar();
this.GetCarCount();
})
}
}

Error + JSON + <select> + <option>

I'm getting a very strange error after I upgraded to Angular 6.0.9. My template has a select, where there is an opnion with a value of "" and an "Select an Option" label, and the other options are generated by a list that comes from the bank.
So when I need to clear the form I call the formBuilder again. However, when I clean the form, a request occurs to api and consequently a json error, warning that it can not serialize a null value.
During the reset of the form I do not call any method that triggers the API, so I'm not sure what to do.
It is worth mentioning that the application still works, but it presents the user with an error message, since I have an interceptor that receives all errors and prints in a snack bar...
Template:
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>
Component:
export class DocumentoDetalheComponent implements OnInit {
docForm: FormGroup;
tiposDocumento: TipoDocumento[];
documento: Documento = new Documento();
constructor(
private fb: FormBuilder,
private tipoDocumentoService: TipoDocumentoService,
private documentoService: DocumentoService,
private route: ActivatedRoute
) {}
ngOnInit() {
const idRota: string = this.route.snapshot.params["id"];
this.createFormGroup();
this.tipoDocumentoService.findAll().subscribe(
obj => {
this.tiposDocumento = obj;
},
error => { }
).unsubscribe;
if (idRota != null){
this.documentoService.findById(idRota).subscribe(
obj => {
this.documento = obj;
this.docForm.setValue({
tipoDocumento: this.documento.tipoDocumento,
resumo: this.documento.resumo,
observacao: this.documento.observacao
});
},
error => { }
);}
}
onSubmit() {
let docTemp: Documento = this.docForm.value;
this.documento.tipoDocumento = docTemp.tipoDocumento;
this.documento.resumo = docTemp.resumo;
this.documento.observacao = docTemp.observacao;
if (this.documento.id == null) {
this.save(this.documento);
} else {
this.update(this.documento);
}
}
save(documento: Documento) {
this.documentoService
.insert(documento)
.subscribe(response => console.log(response));
}
update(documento: Documento) {
this.documentoService.update(documento).subscribe(response => console.log(response));
}
createFormGroup() {
this.docForm = this.fb.group({
tipoDocumento: ["", [Validators.required]],
resumo: ["",[Validators.required, Validators.minLength(5), Validators.maxLength(60)]],
observacao: ["", [Validators.maxLength(500)]]
});
}
limparForm() {
this.createFormGroup();
}
equals(tp1: TipoDocumento, tp2: TipoDocumento) {
return tp1.id === tp2.id
}
voltar() {}
}
API error:
2018-07-16 10:05:43.186 WARN 4996 --- [ tomcat-http--5] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `br.mp.mpce.sge.domain.TipoDocumento` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (''); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `br.mp.mpce.sge.domain.TipoDocumento` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('')
at [Source: (PushbackInputStream); line: 1, column: 579] (through reference chain: br.mp.mpce.sge.domain.Documento["tipoDocumento"])
I found the solution. The problem was in my formGroup, where I was using ngSubmit, so all buttons in my form were submitting API requests. So, the solution was to remove ngSubmir from the form, as well as manually set, in the event (click), the necessary methods.
<form [formGroup]="docForm" novalidate>
<div class="card">
<div class="card-body">
<div class="form-group row" *ngIf="documento?.id != null">
<div class="form-group col-md-3">
<label for="setor">Nº Protocolo: </label>
</div>
<div class="form-group col-md-6">
{{documento?.codigo}}/{{documento?.ano}}
</div>
</div>
<div class="form-group row" *ngIf="documento?.id != null">
<div class="form-group col-md-3">
<label for="setor">Setor cadastro: </label>
</div>
<div class="form-group col-md-6">
{{documento?.setorCadastro?.nome}}
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="selectTipoDocumento">Tipo de Documento: </label>
</div>
<div class="form-group col-md-6">
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>
</div>
<div class="form-group col-md-3 invalid-feedback d-block"
*ngIf="!this.docForm.controls['tipoDocumento'].valid && (this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
Tipo dodocumento é obrigatório
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="inputResumo">Resumo: </label>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" id="inputResumo" formControlName="resumo" placeholder="Resumo do documento" maxlength="60"
autocomplete="off"
[class.is-valid]="this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)"
[class.is-invalid]="!this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)">
</div>
<div class="form-group col-md-3 invalid-feedback d-block"
*ngIf="!this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)">
Resumo é obrigatório (5 a 60 caracteres)
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="inputObservacao">Observação: </label>
</div>
<div class="form-group col-md-6">
<textarea type="text" class="form-control" id="inputObservacao" formControlName="observacao" rows="5">
</textarea>
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
</div>
<div class="form-group col-md-2">
<button class="btn btn-primary btn-block" (click)="limparForm()">Limpar</button>
</div>
<div class="form-group col-md-2">
<button class="btn btn-success btn-block"[disabled]="!docForm.valid" (click)="onSubmit()">Salvar</button>
</div>
<div class="form-group col-md-2">
<a class="btn btn-primary btn-block" [routerLink]="['/']">Voltar</a>
</div>
</div>
</div>
</div>
</form>

Angular 4 - Populate form with JSON data is not working

I have to edit data from a client. I have a form, in which I click on a button and redirects to a Form, in I want it to display the data of that client that I've just clicked.
Thing is, the form builder does not work when I try to associate each key to its value.
However, if I write down the name myself, like, hardcoded, the form builder works like a charm!.
edit-component.ts
import { FuncionForm } from './../../interfaces/funcion_form';
import { FuncionService } from './../../services/funcion.service';
import { Combobox } from './../../interfaces/combobox';
import { ComboboxService } from './../../services/combobox.service';
import { Formulario } from './../../interfaces/formulario';
import { HttpClient } from '#angular/common/http';
import { SharedService } from './../../services/shared-service.service';
import { Component, OnInit } from '#angular/core';
import { Funcion } from '../../interfaces/funcion';
import {
FormGroup,
Validators,
FormBuilder,
FormControl,
FormsModule,
ReactiveFormsModule
} from '#angular/forms';
#Component({
selector: 'app-editar-funcion',
templateUrl: './editar-funcion.component.html',
styleUrls: ['./editar-funcion.component.css']
})
export class EditarFuncionComponent implements OnInit {
funcionCD: number;
dadosFormulario : FuncionForm;
funcionFormGroup: FormGroup;
comboboxProfisArray : Combobox;
comboboxAgrupProfArray : Combobox;
comboboxAgrupCategArray : Combobox;
comboboxNacionArray : Combobox;
myForm : FormGroup;
constructor(private sharedService : SharedService,
private funcionService : FuncionService,
private funcionFormBuilder: FormBuilder,
private comboboxService: ComboboxService)
{}
ngOnInit() {
this.sharedService.currentClientCD.subscribe(message => this.funcionCD = message); // Service to get the client ID
this.funcionService.GetDadosCliente(this.funcionCD).subscribe(
(res:FuncionForm) => {
this.dadosFormulario = res; // Interface to define a client
// This works!
this.myForm = new FormGroup({
nome : new FormControl("A name"),
dt_nasc : new FormControl("1998-02-25"),
sexo : new FormControl("0"),
cd_nacion : new FormControl("PT"),
cd_agrup_prof : new FormControl("M"),
cd_profis : new FormControl("M"),
cd_categ : new FormControl("M"),
loc_trab : new FormControl("A company")
// This works!
/* This doesn't!
this.myForm = new FormGroup({
nome : new FormControl(this.dadosFormulario[0].nome),
dt_nasc : new FormControl(this.dadosFormulario[0].dt_nasc),
sexo : new FormControl(this.dadosFormulario[0].sexo),
cd_nacion : new FormControl(this.dadosFormulario[0].cd_nacion),
cd_agrup_prof : new FormControl(this.dadosFormulario[0].cd_agrup_prof),
cd_profis : new FormControl(this.dadosFormulario[0].cd_profis),
cd_categ : new FormControl(this.dadosFormulario[0].cd_categ),
loc_trab : new FormControl(this.dadosFormulario[0].loc_trab)
*/
})
}
edit-component.html
<div class="container">
<h1>Editar dados do funcionário</h1>
<hr>
<div class="card">
<div class="container">
<div class="row">
<div class="col-md-3" id="col-img">
<img src="/img/1">
</div>
<div class="col-md-9" id="col-dados">
<form class="form-horizontal" role="form" [formGroup]="myForm">
<!--
<div class="form-group row">
<label class="col-md-12 col-form-label">Local de trabalho</label>
<div class="col-md-12">
<input formControlName="loc_trab" type="text" class="form-control">
</div>
</div>
-->
<div class="form-group row">
<label class="col-md-12 col-form-label">Nome</label>
<div class="col-md-12">
<input formControlName="nome" type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-md-12 col-form-label">Data de nascimento</label>
<div class="col-md-12">
<input formControlName="dt_nasc" type="date" class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-md-12 col-form-label">Género</label>
<div class="col-md-12">
<select formControlName="sexo" type="text" class="form-control">
<option value="0">Masculino</option>
<option value="1">Feminino</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-12 col-form-label">Nacionalidade</label>
<div class="col-md-12">
<select formControlName="cd_nacion" type="text" class="form-control">
<option *ngFor="let row of comboboxNacionArray" value="{{ row.cd }}">{{ row.nome }}</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-12 col-form-label">Agrupamento Profissional</label>
<div class="col-md-12">
<select formControlName="cd_agrup_prof" type="text" class="form-control">
<option *ngFor="let row of comboboxAgrupProfArray" value="{{ row.cd }}">{{ row.nome }}</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-12 col-form-label">Profissão</label>
<div class="col-md-12">
<select formControlName="cd_profis" type="text" class="form-control">
<option *ngFor="let row of comboboxProfisArray" value="{{ row.cd }}">{{ row.nome }}</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-12 col-form-label">Categoria Profissional</label>
<div class="col-md-12">
<select formControlName="cd_categ" type="text" class="form-control">
<option *ngFor="let row of comboboxAgrupCategArray" value="{{ row.cd }}">{{ row.nome }}</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-12 col-form-label">Local de trabalho</label>
<div class="col-md-12">
<input formControlName="loc_trab" type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<div class="col-md-12" style="padding-top: 15px;">
<button style="border-radius: 50px; float:right;" type="submit" class="btn btn-primary">Submeter</button>
</div>
</div>
</form>
</div>
</div>
</div>
Some screnshots
Working
Not working
I've searched everywhere and couldn't find a solution.
All help is apreciated!
PS: the JSON data comes like this. Thats why the "0" in this.dadosFormulario[0]
[
{
"nome": "MY NAME",
"dt_nasc": "1978-05-26T00:00:00",
"sexo": "0",
"cd_nacion": "2",
"cd_agrup_prof": null,
"cd_profis": "1",
"cd_categ": "TS",
"loc_trab": ""
}
]
To pre-populate data there are two methods of FormGroup instance. setValue() & patchValue(). After you receive the response from the server just set/patch the values using one of these methods setValue() and patchValue() both sets the value in form control of FormGroup. setValue() sets the value for each and every form control of FormGroup. you cannot omit any form control in setValue() but if you want to assign only few form controls of FormGroup then you can use patchValue().
Modified Code
ngOnInit() {
this.initializeForm();
this.sharedService.currentClientCD.subscribe(message => this.funcionCD = message); // Service to get the client ID
this.funcionService.GetDadosCliente(this.funcionCD).subscribe(
(res:FuncionForm) => {
this.dadosFormulario = res; // Interface to define a client
this.myForm.setValue(
{
nome : this.dadosFormulario[0].nome,
dt_nasc : this.dadosFormulario[0].dt_nasc,
sexo : this.dadosFormulario[0].sexo,
cd_nacion : this.dadosFormulario[0].cd_nacion,
cd_agrup_prof : this.dadosFormulario[0].cd_agrup_prof,
cd_profis : this.dadosFormulario[0].cd_profis,
cd_categ : this.dadosFormulario[0].cd_categ,
loc_trab : this.dadosFormulario[0].loc_trab
})
});
initializeForm()
{
this.myForm = new FormGroup({
nome : new FormControl(),
dt_nasc : new FormControl(),
sexo : new FormControl(),
cd_nacion : new FormControl(),
cd_agrup_prof : new FormControl(),
cd_profis : new FormControl(),
cd_categ : new FormControl(),
loc_trab : new FormControl()
}
Your this.dadosFormulario will be null on onNgOnit(), that's why you are not seeing any value in the form..
You need to use patchValue to update form once you get data from your funcionService