How do I set the first value in the combo?

0

Well, I need a help:

I am trying to set the first state in the combo, I have already put the selected but without success. Can anyone tell me what might be wrong, or something to help me solve.

My code:

<div class="col s6">
     <label>Escolha seu estado</label>
     <select [(ngModel)]="municipio.estado" (change)="buscarCidadesPorEstado($event.target.value)" name="estado" class="browser-default">
     <option selected [value]="e.estado" *ngFor="let e of estados" >{{e.estado}}</option>
     </select>
</div>

I await solution suggestions. Thank you !!

    
asked by anonymous 06.09.2018 / 17:29

3 answers

0
  • go to your controller.
  • in method:
  •      ngOnInit() { 
             //Pode ser que tenha algo aqui.     
             municipio.estado = estados[0];
         }
    

    NOTE: If a request is async that is populating the array of states, assign to the property (municipio.estate) after this array is filled in.

        
    06.09.2018 / 20:07
    0

    To work with select on Angular2 you need to set the compareWith directive and if you need to have a blank initial option add outside ngFor . In that case, it would look like this:

    <div class="col s6">
         <label>Escolha seu estado</label>
         <select [(ngModel)]="municipio.estado" (change)="buscarCidadesPorEstado($event.target.value)" 
            [compareWith]="compareWith" name="estado" class="browser-default">
         <option selected [value]="">Selecione...</option>
         <option [value]="e.estado" *ngFor="let e of estados" >{{e.estado}}</option>
         </select>
    </div>
    

    And in your component:

    compareWith(a: any, b: any): boolean {
        return a && b ? a.id === b.id : a === b;
    }
    

    The compareWith will select the option in the combo automatically when the ngValue changes. The documentation is in this link . I hope I have helped

    Edit: I forgot to warn, use [value] for strings and [ngValue] for objects.

        
    17.09.2018 / 13:22
    0

    Try to put the value attribute of the select tag with the value you want it to load selected:

    <div class="col s6">
         <label>Escolha seu estado</label>
         <select [(ngModel)]="municipio.estado" value="municipioSelecionado" (change)="buscarCidadesPorEstado($event.target.value)" name="estado" class="browser-default">
         <option selected [value]="e.estado" *ngFor="let e of estados" >{{e.estado}}</option>
         </select>
    </div>
    

    where the selectedMunicipality is a variable with the state id to load pre-selected.

    - Related question.

    - Here's an example

        
    18.09.2018 / 19:26