如何在 Angular 8 中的选择标签上设置占位符?



>我正在创建一个下拉列表来过滤数据,所以我创建了一个下拉列表

<form  #filter="ngForm" (ngSubmit)="filterta(filter)" style="display: flex;">
<select  ngModel #month="ngModel" name="month" required  >
<option [ngValue]="null" [disabled]="true" >All</option>
<option value="1">January</option>
</select>
</form>

当我删除这些属性表单选择标签ngModel #month="ngModel"时,它会显示占位符选项"全部",当我添加这些属性时,它在占位符中显示为空白。

这在 Angular-10 中对我有用。

<select class="form-control" name="role" id="role" formControlName="role">
<option value="" disabled selected>Select the role</option>
<option *ngFor="let role of roleList" value="{{ role }}">{{role}}</option>
</select>

component.ts中设置初始值month = null,并在component.htmlselect标记中添加[(ngModel)]="month"

组件.ts

month = null;

组件.html

<form  #filter="ngForm" (ngSubmit)="filterta(filter)" style="display: flex;">
<select name="month" [(ngModel)]="month" #month required>
<option [ngValue]="null" [disabled]="true" >All</option>
<option value="1">January</option>
</select>
</form>

尝试如下:

  • ngModel #month="ngModel"修改为[(ngModel)]="selectedMonth" #month
  • 在 .ts 文件中,添加selectedMonth = null;

.ts

selectedMonth = null;

。.html

<form  #filter="ngForm" (ngSubmit)="filterta(filter)" style="display: flex;">
<select  [(ngModel)]="selectedMonth" #month name="month" required  >
<option [ngValue]="null" [disabled]="true" >All</option>
<option value="1">January</option>
</select>
</form>

工作演示

当模型没有初始值时,这对我有用

<select [(ngModel)]="myModel">
<option [ngValue]="undefined" [disabled]="true">Choose Type</option>
<option *ngFor="let type of typeList; let i = index;" [value]="type.value">{{type.label}}</option>
</select>

你需要稍微改变一下你的代码

网页文件

[(ngModel)]="month" // This will set month value for select tag

在 TS 文件中

将月值设置为您想要的任何值

month = null;

工作代码

https://stackblitz.com/edit/angular-plwvgg

这对我来说很好用

> <select [(ngModel)]="name">      
> <option value="" disabled selected hidden>Choose your number</option>   
> <option value="red">One</option>    
> <option value="green">Two</option>     
> <option value="black">Three</option> 
></select>

<select id="district" class="form-control">
<!-- <option [disabled]="true">Select District/City</option> -->
<option hidden value="" disabled selected>Select District/City</option>
<option *ngFor="let postoffice of filterPostOffice" [value]="postoffice.District">
{{ postoffice.District }}
</option>
</select>

"选择"中的占位符

这对我来说很好用:

<option value="" disabled selected>Text to display</option>

在 Angular 中,要充当占位符的选项设置value="undefined"并将其放置在最顶部,如下所示:

<select
id="fmonthsCommitment"
name="support"
class="inp-si"
(click)="commitmentNotification()"
[(ngModel)]="commitmentInMonthsInput"
>
<option value="undefined" disabled selected>
Choose Months Commitment...
</option>
<option value="3">3</option>
<option value="6">6</option>
<option value="12">12</option>
<option value="24">24</option>
</select>

最新更新