Reputation: 1184
I'm adding a child component to a parent component form.
<form [formGroup]="usuarioForm" novalidate>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputNome">Nome</label>
<input type="text"
formControlName="nome"
class="form-control "
placeholder="Nome" />
</div>
</div>
<endereco [enderecoGroup]=usuarioForm></endereco>
<button type="submit"
class="btn btn-default"
(click)="InsereUsuario(usuarioForm.value)">
Enviar
</button>
</form>
<h4>Endereço</h4>
<div class="col-md-2">
<div class="form-group" [formGroup]="enderecoGroup">
<label for="exampleInputCep">Cep</label>
<input type="text"
class="form-control"
placeholder="Cep"
(blur)="GetAdress($event.target.value)">
</div>
</div>
<div class="col-md-4">
<div class="form-group" [formGroup]="enderecoGroup">
<label for="exampleInputComplemento">Complemento</label>
<input type="text"
class="form-control"
placeholder="Complemento"
[value]=endereco?.complemento>
</div>
</div>
@Input() enderecoGroup: FormGroup;
endereco: Endereco
GetEndereco(Cep: string) {
this.servico.GetEndereco(Cep)
.subscribe(resposta => this.endereco = resposta);
}
When submitting the form the Adress.html entries are blank, what should I do?
I'm using React forms
Upvotes: 10
Views: 1044
Reputation: 1184
Reading the Angular documentation on React Forms, I discovered that:
Populate the form model with setValue()
and patchValue()
I'm using patchValue()
:
GetEndereco(Cep: string) {
this.servico.GetEndereco(Cep)
.subscribe(response => {
this.enderecoGroup.patchValue({
bairro: response.bairro,
logradouro: response.logradouro,
cidade: response.localidade
});
});
}
Print:
Upvotes: 2
Reputation: 9392
I did it in what I think it is an better way. Creating an inside group for address and passing just that to the address component.
.TS
this.usuarioForm = this.formBuilder.group({
nome: this.formBuilder.control('', [Validators.required, Validators.minLength(3)]),
sobreNome: this.formBuilder.control('', [Validators.required]),
emailAdress: this.formBuilder.control('', [Validators.required, Validators.email]),
tipoPessoa: this.formBuilder.control('1', [Validators.required]),
endereco: this.formBuilder.group({ // Another form group inside the bigger group for better encapsulation.
cep: this.formBuilder.control('', [Validators.minLength(8), Validators.maxLength(9)]),
logradouro: this.formBuilder.control('', [Validators.required]),
bairro: this.formBuilder.control('', [Validators.required]),
cidade: this.formBuilder.control('', [Validators.required]),
complemento: ''
})
});
get endereco() {
return this.usuarioForm.get('endereco') as FormGroup; // this is just a refence to the inside group that contains information just relavant to address
}
Html:
<endereco [enderecoGroup]=endereco></endereco> //pass just the inside formGroup
In this way there is no need to listen to changes in the child component
Upvotes: 1