通过 CSS 覆盖默认的样式,并使用 ng-deep 伪类选择器来修改 MatInput 组件。以下是代码示例:
/* 通过 CSS 覆盖默认样式 */
.mat-form-field-infix {
position: relative;
}
/* 使用 ng-deep 伪类选择器 */
::ng-deep .mat-form-field-label-wrapper {
position: absolute !important;
top: -1.4em;
}
在 HTML 模板中,将 MatInput 标签放在 MatFormField 内,并在 MatFormField 上添加 floatLabel="always" 属性。注意在组件中引入 Angular 的 ViewEncapsulation.None 模块,以确保 CSS 样式的全局性。
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
...,
encapsulation: ViewEncapsulation.None, // 引入 ViewEncapsulation 模块
})
export class MyComponent {
...
}
姓名: