Angular 6 - Load Reactive Form after Http request

0

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:

link

link

    
asked by anonymous 19.10.2018 / 20:59

0 answers