Default option in select with Angular 5

0

I have the following problem, I hope you can help me:

I have a form in my HTML template:

    <form #formulario="ngForm" autocomplete="off">
        <div>
            <label for="periodo">Periodo</label>
            <select id="periodo" #periodo ngModel required name="periodo">
                <option *ngFor="let periodo of periodos" [value]="periodo.id">{{periodo.fecha_inicio}}</option>
            </select>
        </div>
    </form>

And I would like to know how I can define a default option in my select . I have already tried adding the attribute [selected]="defaultValue" but I do not get the expected result.

Any suggestions are welcome ...

SOLUTION

Ok, I could solve it. I'll leave my answer in case it helps someone:

I defined in my file .ts a variable with the value that I hope to set by default:

defaultValue = val;

and in my template HTML

 <form #formulario="ngForm" autocomplete="off">
        <div>
            <label for="periodo">Periodo</label>
            <select id="periodo" #periodo ngModel required name="periodo">
                <option *ngFor="let periodo of periodos" [value]="periodo.id" [selected]="default == paralelo.descripcion">{{periodo.fecha_inicio}}</option>
            </select>
        </div>
    </form>
    
asked by Joel Muñoz Moran 27.07.2018 в 01:42
source

1 answer

1

You can do this by creating an "index" and then link it to the [selected] option.

Also, note the change I made in the ngFor, since you did not close the quotes.

<option *ngFor="let periodo of periodos; let index = index" [value]="periodo.id" [selected]="index == 1" >{{periodo.fecha_inicio}}</option>

I hope it serves you.

    
answered by 27.07.2018 / 02:02
source