I am having trouble displaying a list of clients obtained by a GET request in a select component. Because GET is asynchronous, the form is being built before the request is finished and hence the select is empty. If I refresh the page, the list of clients appears.
Component excerpt:
form: FormGroup;
clientes: Cliente[];
constructor(
private formBuilder: FormBuilder,
private clienteService: ClienteService
){}
ngOnInit() {
this.clienteService.findAll()
.subscribe(clientes => {
this.clientes = clientes
});
this.initForm();
}
initForm(){
this.form = this.formBuilder.group({
cliente: this.formBuilder.control('')
}, { updateOn: 'blur' });
}
If I put the call to initForm()
in subscribe , a delay occurs to initialize the form and thus I get the error:
ERROR Error: formGroup expects a FormGroup instance. Please pass one in.
Excerpt from my select:
<div class="input-field col s6">
<select id="cliente" formControlName="cliente">
<option disabled selected>Selecione um cliente...</option>
<option *ngFor="let cli of clientes" [value]="cli.id">
{{ cli.nome }}
</option>
</select>
<label for="cliente">Cliente</label>
</div>
I'm using Angular 6 with Materialize CSS. I have tried to apply the solutions suggested in the links below, but none worked: