passing value webapi to select html in angular 2

0

I have a function in typescript 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>

Thank you in advance: D

    
asked by anonymous 23.05.2018 / 15:50

1 answer

1

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

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

<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 dependency of formBuilder and create a FormGroup with the name defined in the [formGroup] of the Html.

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

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

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

Upon receiving the data from your WebAPI you could add the data to the select as follows:

this.testes = res;

Take advantage of and take a look at the reactive forms documentation link

    
23.05.2018 / 16:13