简体   繁体   中英

Angular select placeholder not showing

I am trying to add a select that shows a placeholder by default like this:

<select id="type" formControlName="type">
  <option hidden value="" [disabled]="true" [selected]="true">Placeholder</option>
  <option *ngFor="let item of ['test 1', 'test 2']" [value]="item">{{ item }}</option>
</select>

I don't see Placeholder in the select when I load the page. But if I do:

<select id="type" formControlName="type">
  <option hidden value="" [disabled]="true" [selected]="true">Placeholder</option>
  <option>test 1</option>
  <option>test 2</option>
</select>

I see it. What is wrong with *ngFor that it does not show the placeholder?

I faced similar problems with the select placeholder and each time had different solutions working. Try just leaving the disabled and selected (remove the hidden) or maybe assign to your FormControlName an initial dummy value like -1 and then set the placeholder option value to -1.

I'm using A14 and NonNullableFormBuilder. There I set the default value for the formControlName to -1 when initializing the control on the FormBuilder and then add -1 to the value attribute of the default option to show. Then you can set a validator value for checking if the value is higher than -1.

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