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
We can use the :host pseudo-selector to combine a set of CSS classes to define possible child styles inside the child component itself. And then we can trigger these classes from outside by applying the style we want to the <child> host element. Angular provides a way to bind a single css class to an host element.
Otherwise, remember the three steps: Prepare Child component to emit data. Bind Property in Parent Component template. Use Property in Parent Component class.
While there is no direct way to pass data from the child to the parent component, there are workarounds. The most common one is to pass a handler function from the parent to the child component that accepts an argument which is the data from the child component.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With