1

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.

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
Julio Rodríguez
  • 447
  • 1
  • 8
  • 23
  • 2
    Does this answer your question? [Angular 4 - Select default value in dropdown \[Reactive Forms\]](https://stackoverflow.com/questions/47011521/angular-4-select-default-value-in-dropdown-reactive-forms) – Matt U Dec 02 '19 at 02:47

2 Answers2

1

It is very simple. you can do something like this.

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

StackBlitz

Update - Using Reacting Forms

As you are using Angular Reactive Forms you can use features of reactive forms to do what you want. In your case you can set selected option to select as below.

HTML

<form [formGroup]="myForm">
  <select formControlName="mySelect">
    <option *ngFor="let coutry of countries" [value]="coutry">{{coutry}}</option>
  </select>
</form>

TS

  countries: any = ['Sri Lanka', 'USA', 'UK', 'Australia'];
  selectedCoutry = 'Australia';

  myForm: FormGroup;

  constructor() {

    this.myForm = new FormGroup({
      mySelect: new FormControl('')
    });
  }

  ngOnInit() {
    this.myForm.get('mySelect').setValue(this.selectedCoutry);
  }

StackBlitz

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
1

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

bryan60
  • 28,215
  • 4
  • 48
  • 65