Use Angular fontawesome icon in input placeholder text

2.9k Views Asked by At

I'm using official Font Awesome Angular components in Angular 6 application.
But I can't find way to add a search icon as placeholder to an input element except adding fontawesome fonts additionally to my app, that is not desirable.

  <div class="search-box">
    <input type="search" [(ngModel)]="searchText" placeholder="&#xf002; Search" />
  </div>
2

There are 2 best solutions below

1
On

Install official font-awesome

npm install @fortawesome/fontawesome-free -s

Import font-awesome to your styles.css

@import '@fortawesome/fontawesome-free/css/all.min.css';

Now you can use font-awesome normal way and search icons from the official site.

0
On

So I come up with such workaround: instead of

  <div class="search-box">
    <input type="search" [(ngModel)]="searchText" placeholder="&#xf002; Search" />
  </div>

I add placeholder in adjacent block

  <div class="search-box">
    <input class="search-box-input" type="search" [(ngModel)]="searchText"/>
    <div class="search-box-placeholder-wrapper">
      <fa-icon [icon]="faSearch" class="search-box-placeholder"></fa-icon>
      <span>&nbsp;Search</span>
    </div>
  </div>

and added additional css styles

.search-box {   
   position: relative;

  &-placeholder-wrapper {
    pointer-events: none;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 8px;  
   }

  &-input:focus + .search-box-placeholder-wrapper {
    display: none;  
  } 
}