简体   繁体   中英

Angular - select placeholder not showing


is there any reason why this simple code won't work? I'm trying to have a placeholder on my select, but it simply shows as one of the other options in the list.

<div *ngFor="let d of formDatiRichiesta" class="form-row">
          <select *ngIf="d.type=='select'" 
                  class="form-control" 
                  name="{{d.name}}" 
                  [(ngModel)]="model[d.name]"
                  required>
            <option selected disabled>{{d.placeholder}}</option>
            <option *ngFor="let b of elencoBanche" value="{{b.id}}">{{b.denominazione}}</option>
          </select>
        </div>

I'm using angular4 . Thanks.

--EDIT-- I found out that if I delete [ (ngModel)]="model[d.name]" all works fine. Any hint?

You have to set the value of the <option> to the value of the model, because the <select> will use the value of the model as the default selection.

When the model is undefined at the beginning you can do it like this:

<option value="undefined">Please choose...</option>

That's how it is supposed to work. With the attribute disabled you can't choose it as an option.

But you could add the hidden attribute to also hide it:

<option value="" selected disabled hidden>{{d.placeholder}}</option>
 <select formControlName="value"  class="form-control"
                    style=" height: 40px">
                      <option [ngValue]="null" selected disabled hidden>Select</option>
                      <option>Save</option>
                      <option>Download</option>

                    </select>

Add this simply it will work.

<option value="" disabled>Select Category</option>

Or

<option [ngValue]="null">Select Category</option>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM