Angular Material: 如何将 floatPlaceholder 设置为从不

Angular Material: how to set floatPlaceholder to never

图书馆:Angular Material (material2)

我想使用 MdInputContainer 的 floatPlaceholder 指令,这样 placeholder/hint 永远不会浮动。

我没看到它在文档中的什么地方说明了它期望的值:

@Input() floatPlaceholder: Whether the placeholder should always float, never float or float as the user types.

取自:https://material.angular.io/components/input/api

<md-input-container [floatPlaceholder]="false">
  <input type="text" mdInput placeholder="Search...">
</md-input-container>

我已经尝试 false"never" 作为我最好的猜测值,但都不能阻止占位符浮动在输入上方。

您可以将 floatPlaceholder 输入设置为:自动、始终、从不。

<md-input-container floatPlaceholder="never">
          <input type="text"
                 mdInput
                 placeholder="Search...">
</md-input-container>

更新 (Angular Material 6):

现在你必须使用 floatLabel:

<mat-form-field floatLabel="never">
    <input matInput placeholder="Search...">
</mat-form-field>

Stackblitz Demo

您也可以在 AppModule 中将其设置为全局设置,如下所示:

MAT_FORM_FIELD_DEFAULT_OPTIONS 导入您的 AppModule

import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material';

传入模块的providers数组(...省略附加代码):

@NgModule({
  imports: [...],
  declarations: [...],
  providers: [
    { provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { float: 'never' } },
    ...
  ],
  bootstrap: [...]
})
export class AppModule {}

对于Angular 10 这很好用

import { NgModule } from '@angular/core';
import { MatAutocompleteModule } from '@angular/material/autocomplete';


  @NgModule({
    exports: [
      MatAutocompleteModule,
      // other modules needed
    ],
  providers: [
    { provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { floatLabel: 'never' } },
  ],
  declarations: [],
})
export class MaterialModule { }