首页 > 解决方案 > Angular Material mat-form-field 输入字段图标

问题描述

在 Angular 项目中,我有Angular Material mat-form-field我的图标出现在<input>字段的左侧外部,右侧有占位符:

<mat-form-field appearance="fill" class="fld">
  <mat-icon matPrefix class="my-icon">sentiment_very_satisfied</mat-icon>
  <input
    matInput 
    placeholder="myPlaceholder"
    class="inp"
  />
</mat-form-field>

我试图弄清楚如何将图标放在<input>同一左侧的标签字段中matPrefix

我试过了:

<mat-form-field appearance="fill" class="fld">
  <input
    matInput
    placeholder="myPlaceholder"
    class="inp"
  >
    <mat-icon matPrefix class="my-icon">sentiment_very_satisfied</mat-icon>
  </input>
</mat-form-field>

错误 NG5002:无效元素没有结束标签“输入”

也许如果我必须使用<md-input-container>我已经尝试过import { MdInputModule } from '@angular/material';app.module.ts没有以这种方式加载。

'MdInputModule' 已声明但其值从未被读取

由于我有一些定制设计,这是我的my-comp.component.scss

mat-form-field {
  width: 100%;
  background-color: #da2ba6;
}

::ng-deep .mat-form-field-infix {
  top: -3px;
  background-color: #da2ba6;
}

.inp {
  width: 90%;
  height: 34px;
  border-radius: 20px;
  background: #fff;
  text-align: right;
}

.my-icon {
  z-index: 1;
  position: relative;
}

.fld {
  width: 100%;
}

这是实际结果,出现在外面:

在此处输入图像描述

并且期望的结果在输入字段内的右侧,与占位符在一行中,该占位符已经存在于右侧,也在输入字段内(只是不包括在图像中):

在此处输入图像描述

任何意见将是有益的

标签: angularangular-materialiconsinput-field

解决方案


<input>是一个 void 元素:它并不意味着包含元素。这意味着不允许现有的结束标签</input>

您必须删除此结束标签并将您的<mat-icon>标签放在之后(同时仍然放在 mat-form-field 标签中):

<mat-form-field appearance="fill" class="fld">
  <input
    matInput
    placeholder="myPlaceholder"
    class="inp"
  >
  <mat-icon matPrefix class="my-icon">sentiment_very_satisfied</mat-icon>
</mat-form-field>

这是当前带有前缀和后缀的官方示例:

<form class="example-form">
  <mat-form-field class="example-full-width">
    <mat-label>Telephone</mat-label>
    <span matPrefix>+1 &nbsp;</span>
    <input type="tel" matInput placeholder="555-555-1234">
    <mat-icon matSuffix>mode_edit</mat-icon>
  </mat-form-field>
</form>

推荐阅读