
本文介绍如何在 angular 的 material 输入框中显示一个不可编辑、不可删除的默认前缀(如 ####),同时允许用户在前缀后自由输入和编辑后续内容,通过 css 定位与内边距配合实现视觉隔离与交互限制。
本文介绍如何在 angular 的 material 输入框中显示一个不可编辑、不可删除的默认前缀(如 ####),同时允许用户在前缀后自由输入和编辑后续内容,通过 css 定位与内边距配合实现视觉隔离与交互限制。
在 Angular 应用中,常需为输入框设置“只读前缀”——例如编号规则中的固定前缀(如 INV-、USR- 或 ####),该部分由系统生成、不可被用户删除或修改,但用户可在其后追加自定义内容(如 ####123456)。原生 <input> 不支持局部只读,而 matInput 本身也不提供内置前缀锁定机制。此时,推荐采用 CSS 视觉模拟 + 结构分离 的方案:将前缀渲染为绝对定位的 <span>,输入框本体则通过 padding-left 预留空间,确保用户输入始终出现在前缀右侧,且无法覆盖或删除前缀。
以下为完整实现步骤:
✅ HTML 结构(语义清晰,兼容表单控件)
<mat-form-field appearance="outline" class="col-30 placeholder-prefix" id="mat-identifier">
<span class="prefix">{{ selectedIdentifier?.standardIdentifier || '####' }}</span>
<mat-label>
{{ 'columns.dashboard.identifier' | translate }}
<span *ngIf="selectedIdentifier?.mandatorieIdentifier">*</span>
</mat-label>
<input
matInput
formControlName="identifier"
maxlength="255"
(input)="limitcarateres('identifier', 255, $event)"
/>
<mat-hint *ngIf="showPackage !== true && selectedIdentifier && selectedIdentifier?.tag !== 'OTHERS'">
{{ selectedIdentifier?.standardIdentifier }}
<span *ngIf="dataCorrespondenceForm.get('identifier').value">
-{{ dataCorrespondenceForm.get('identifier').value }}
</span>
</mat-hint>
</mat-form-field>? 注意:[value] 绑定已移除,改由 <span class="prefix"> 承担静态前缀展示职责;formControlName 仍绑定完整输入值(含用户输入部分),业务逻辑无需改造。
✅ SCSS 样式(精准控制定位与聚焦状态)
.placeholder-prefix {
.mat-mdc-form-field-input-control {
padding-left: 50px; // 为前缀预留水平空间
}
.prefix {
position: absolute;
left: 12px; // 与 input 左侧对齐(需根据 label 高度微调)
top: 29px; // 默认未聚焦时 label 位置
font-size: 14px;
color: rgba(0, 0, 0, 0.6); // 匹配 hint 文字灰度
pointer-events: none; // 确保不拦截光标事件
}
.mat-mdc-form-field-infix {
display: flex;
}
// 聚焦状态下 label 上浮,前缀需同步上移并放大
&.mat-focused .prefix {
top: 24px;
font-size: 12px;
}
// 可选:禁用用户选中前缀(增强“不可编辑”感知)
& .prefix::selection {
background: transparent;
}
}⚠️ 关键注意事项
-
前缀非表单值:<span class="prefix"> 仅用于展示,formControl.value 仅包含用户实际输入的内容(不含前缀)。若后端需完整字符串(如 ####123456),应在提交前拼接:
const fullValue = this.selectedIdentifier?.standardIdentifier + this.form.get('identifier')?.value; - 响应式适配:top 值需根据 mat-label 的实际高度动态调整(Material v15+ 使用 mat-mdc-* 类名,高度可能变化),建议用 DevTools 实时校准。
- 无障碍访问:当前方案对屏幕阅读器不够友好。如需增强可访问性,可添加 aria-hidden="true" 到 .prefix,并在 <mat-label> 中明确说明前缀规则(如 "Identifier (starts with ####)")。
- 不推荐 readonly + value 绑定:虽可阻止编辑,但会禁用全部输入,且无法实现“前缀锁定 + 后缀可编辑”的混合行为。
该方案轻量、无侵入性,兼容 Angular Material 最新版(v15+),无需引入额外依赖或自定义指令,是实现“不可清除默认前缀”的最佳实践。

















