passing webapi value to select html in angular 2

Asked

Viewed 67 times

0

i have a typescript function that receives a json value from my webapi, and I need to pass this result to a select in html...

Service:

teste: teste[];
public getNomes(type: string, formGroup: FormGroup) {
    let params: HttpParams = undefined;
    params = new HttpParams().set('type', type);
    switch (type) {
        case "teste":
            params = params.set('cod', formGroup.controls['codigoCliente'].value);
            this.retornaNomeApi(API + '/Pesquisa/SelectPesquisa', params).subscribe(nome => {this.teste = nome.result});
    }
}

HTML:

 <select class="form-control" name="pedido">
        <option selected>Selecione...</option>
        <option *ngFor="let testes of teste">{{testes.cod}} - {{testes.nome}}</option>
      </select>

thanks in advance :D

1 answer

1


I believe the best way to do that would be to create a reactive form. You could do it this way.

In HTML you could create the form with a formGroup this way.

<form [formGroup]="form">` 
     <select class="form-control" formGroupName="pedido">
        <option selected>Selecione...</option>
        <option *ngFor="let testes of teste">{{testes.cod}} 
          {{testes.nome}}</option>
   </select>
</form> 

In typescript you would need to inject the formBuilder dependency and create a Formgroup with the name set in the [formGroup] of Html.

constructor(private fb:FormBuilder){
}
form: FormGroup;

And add the instance of your form within the ngOnInit method().

ngOnInit(){
 this.form = this.fb.group({ 
    pedido: ''
 })
}

In receiving the data from your Webapi you could add the data to select as follows:

this.testes = res;

Take a look at the documentation of the reactive Forms https://angular.io/guide/reactive-forms

  • Dude, I tried that way, but it still doesn’t get any feedback

  • Sorry for the obviousness, but there is indeed the return of API data?

  • yes, I can see the return of the api in the browser sources

  • Bruno, add in the HTML above the form this code {{ form.value | json }} and see if it shows the request value as empty.

  • it shows empty.

  • add this.form.Controls['request']. setValue(this.tests[0], { onlySelf: true }); inside the request subscribe. Theoretically it has to set the 0 position of your array as the default of your select

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.