Search code examples
angulartypescriptangular2-formsngfor

how can I apply the select directive to the first option generated by a *ngFor?


I have a select whose options are generated for the data returned by an HTTP request in the ngOninit hook.

it looks like this:

  ngOnInit() {
    this.documentosService.buscaParametros(this.request).subscribe(res => {
    this.tipoDocumento = res["general"];

  }

this is the HTML code:

   <select class="form-control pv-0" formControlName="tipoFactura" name="tipoFactura">    
        <option *ngFor="let documento of tipoDocumento">
          {{documento.par_deslargo01}}</option>
      </select>

If it wasn't generated dynamically I could just write the selected directive to the first option element, but in this case I don't know how to achieve it. I need that when the component first load the first option is selected.

How could achieve this? Thanks.


Solution

  • to answer the question posed, ngFor exposes a number of helpful template variables, among them is "first" which which is true if you're on the first item, false otherwise:

    <option *ngFor="let documento of tipoDocumento; let first" [selected]="first">
          {{documento.par_deslargo01}}</option>
    

    also last, index, even and odd are offered.

    but, since you're using reactive forms, the recommended method is to skip all that and set the form control value:

    ngOnInit() {
      this.documentosService.buscaParametros(this.request).subscribe(res => {
        this.tipoDocumento = res["general"];
        this.form.get('tipoFactura').setValue(this.tipoDocumento[0].par_deslargo01)
        // not sure what your form variable really is
      }
    }
    

    this will automatically select that value in your list of options