Angular中mat-form-field内input的placeholder不生效问题求助
问题原因
当input嵌套在mat-form-field内部时,Angular Material会忽略input原生的placeholder属性,转而通过mat-label组件实现占位符/浮动标签功能。你的代码使用了空的mat-label,同时试图通过input的placeholder显示文本,这直接导致占位符无法正常渲染。
修复方案
- 将空的
mat-label替换为目标占位符文本 - 移除
input上的placeholder属性 - 保留
floatLabel="never"可让标签始终停留在占位符位置(不会在输入框获焦或有内容时上浮)
修正后的代码
<mat-form-field class="search" floatLabel="never"> <mat-label>Search here</mat-label> <input class="search-input" matInput value="" id="search" name="search" type="text" (change)="inputChange($event)" [(ngModel)]="searchText" [matAutocomplete]="auto" (input)="onChange()"> <mat-autocomplete #auto="matAutocomplete"> <mat-option [hidden]="!showPeople" (click)="submitSearch()" [value]="getFullName(user)" *ngFor="let user of persons"> <mat-icon class="option">person</mat-icon>{{getFullName(user)}} </mat-option> <mat-option [hidden]="!showEvents" (click)="submitSearch()" [value]="event.eventName" *ngFor="let event of events"> <mat-icon class="option">event</mat-icon>{{event.eventName}} </mat-option> </mat-autocomplete> <button type="button" (click)="submitSearch()" mat-icon-button matSuffix class="search-button"> <mat-icon><span style="font-weight: bolder;">search</span></mat-icon> </button> </mat-form-field>
补充说明
- 使用
mat-label符合无障碍访问规范,能正确将标签文本与输入框关联 - 若希望输入框获焦或有内容时标签自动上浮,只需移除
floatLabel="never"属性(默认行为为auto)
内容的提问来源于stack exchange,提问作者kawlorridor
相关产品推荐
相关产品推荐

