How to set the first value in the combo?

Asked

Viewed 1,253 times

1

Guys, I need some help:

I’m trying to set the first state in the combo, I’ve put Selected but without success. Can someone 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 suggestions for solutions. Thank you!!

  • 1

    The way your code is, all "options" are tagged "Selected" - which is not desirable, you can remove "Selected" and set the initial value directly in "municipio.estado" (in typescript).

  • 1

    What is the angular version?

  • Wallacemaxters is 5 the version I’m working on

3 answers

0

To work with select in Angular2 you need to put the directive compareWith and if you need to have a blank initial option add outside the ngFor. In your 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 its component:

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

The compareWith will automatically select the option in the combo when the ngValue amend. The documentation is at this link. I hope I’ve helped

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

0

Try placing 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 id of the state that must load pre-selected.

- Related question.

- Follow an example

0

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

NOTE: If it is an async request that is filling the array of states, assign it to the property (municipio.estado) after this array is filled in.

Browser other questions tagged

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