简体   繁体   中英

How to put icon in placeholder in Angular Material?

I'm trying to put icon in placeholder. I tried this code:

<md-input name="name">
   <md-placeholder>
      <i class="material-icons app-input-icon">face</i> Name
   </md-placeholder>
</md-input>

It was working (was showing icon with placeholder) before I reinstalled angular material and updated the angular cli. For this code browser is giving this error now: "'md-input' is not a known element".

then I tried this code:

 <md-input-container>
    <input mdInput placeholder="Name" name="name2">
 </md-input-container>

It is working properly but How can I put 'face' icon in its placeholder ?

Your problem was not the md-placeholder tag. Just like the error said, it was md-input which was deprecated. Angular Material recently changed his md-input tag into a mdInput directive.

But the md-placeholder is still working (not sure if it will last though).

The following code should work then :

<md-input-container>
    <md-placeholder>
        <md-icon>face</md-icon> Name
    </md-placeholder>
    <input mdInput name="name">
</md-input-container>

An alternative is to use the mdPrefix or mdSuffix directives to your md-icon tag. That will display your icon on the left or right of your input, but it won't follow the placeholder when you click on it.

Example :

<md-input-container>
    <md-icon mdPrefix>face</md-icon>
    <input mdInput placeholder="Name" name="name">
</md-input-container>

Check the API reference for more informations.

Angular 6

.example-full-width {
  width: 100%;
}
<mat-form-field  class="example-full-width">
 <mat-icon matPrefix>email</mat-icon>
  <input matInput
   type="email"
   tabindex="1"
   placeholder="Your Email"
   formControlName="email">
</mat-form-field>

mat-suffix didn't work for me either. Keeping up with their docs is always a chore, but as of 5.1.1 this should work:

<mat-form-field class="example-form-field">
  <input matInput type="text" placeholder="Clearable input" [(ngModel)]="value"/>
  <button mat-button *ngIf="value" matSuffix mat-icon-button aria-label="Clear" (click)="value=''">
    <mat-icon>close</mat-icon>
  </button>
</mat-form-field>

Source: "Input with a clear button" example here: https://material.angular.io/components/input/examples

<div>
    <mat-toolbar class="table-search">
        <span class="fileter-width"><mat-form-field>
                    <input matInput [(ngModel)] = "value"  placeholder="Search">
                    <button mat-button class="remove-search" matSuffix  mat-icon-button aria-label="Clear" (click) = "value=''">
                        <i class="fa fa-remove"> </i>
                    </button>
                </mat-form-field></span>
    </mat-toolbar>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM