【问题标题】:mat-autocomplete auto-hide placeholder text on input focusmat-autocomplete 在输入焦点上自动隐藏占位符文本
【发布时间】:2018-08-26 17:33:31
【问题描述】:

根据文档中的示例,我正在使用带有输入的 mat-autocomplete 组件,并且我已将输入配置为使用标签并具有非浮动占位符文本,如下所示:

<mat-form-field floatLabel="never">
  <input 
    type="text" 
    placeholder="Search..." 
    aria-label="Number" 
    matInput 
    [formControl]="search" 
    [matAutocomplete]="auto">
  <button 
    mat-button 
    *ngIf="search.value" 
    matSuffix 
    mat-icon-button 
    aria-label="Clear" (click)="clearSearch()">
      <mat-icon>close</mat-icon>
  </button>
  <mat-autocomplete 
    #auto="matAutocomplete" 
    (optionSelected)="goToResult($event)">
    <mat-option 
      *ngFor="let result of searchResults" 
      [value]="result">
      {{result.id}}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

当点击输入开始输入字符时,占位符不会消失,直到我输入第一个字符。我是否缺少一些应该设置的配置\属性?

或者我需要设置一个占位符值绑定并自己设置\清除它?

谢谢

【问题讨论】:

  • 这是正常的执行方式。 Endeed,占位符只会在输入第一个字符时消失。

标签: angular angular-material2 angular-material-6


【解决方案1】:

您可以删除输入中的占位符并在mat-form-field 中添加mat-placeholder 并使用类自定义css。

HTML 文件:

<form class="example-form">
  <mat-form-field floatLabel="never">
      <input 
        matInput 
        type="text" 
        aria-label="Number" 
        matInput [formControl]="myControl" 
        [matAutocomplete]  ="auto">

      <mat-placeholder class="placeholder">Search</mat-placeholder>

      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of options" [value]="option">
          {{option}}
        </mat-option>
      </mat-autocomplete>
  </mat-form-field>
</form>

CSS 文件:

.mat-focused .placeholder {
    color: transparent;
}

.example-form {
  min-width: 150px;
  max-width: 500px;
  width: 100%;
}

.example-full-width {
  width: 100%;
}

【讨论】:

  • 在Blur上可以看到浮动标签
  • 在长占位符用省略号(“...”)呈现的情况下,这对我不起作用,因为点没有隐藏。我不得不改用这个 CSS: .mat-focused .placeholder { display: none; }
【解决方案2】:

使用 OOTB matInput 并仅隐藏占位符“on-float”

/*hide the floating mat input part */
.mat-form-field-should-float .mat-form-field-label-wrapper {display: none;}

完整的解决方案

.middle-cut .mat-form-field-should-float .mat-form-field-label-wrapper {display: none;}
.middle-cut .mat-form-field-should-float .mat-form-field-infix {    margin-top: -10px;}
.middle-cut .mat-form-field-infix  {border:0; padding-top:0; padding: .1375em 0; }
.middle-cut .mat-form-field-label{top: 0.85em;}

【讨论】:

    【解决方案3】:

    您可以使用 mat-placeholder 并通过在 (focus) 事件上添加一个类来隐藏它,这将隐藏占位符。看这个链接https://stackoverflow.com/a/60021883/9026103

    【讨论】:

      猜你喜欢
      • 2012-03-31
      • 2021-02-15
      • 1970-01-01
      • 2012-09-14
      • 2019-05-11
      • 2016-02-12
      • 2020-06-01
      • 2019-11-27
      • 2017-07-03
      相关资源
      最近更新 更多