I am creating a directive in Angular 7 that will place a magnifying glass icon in an input. I'd like it to work like this:
<input type="text" search-icon />
I am currently using font-awesome. To use an icon in font-awesome, you would import the icon into a component and then use that icon as the attribute in the icon tag:
import {faSearch} from 'fontawesome/some/dir';
@Component({
selector: 'app-component',
template: '<fa-icon [icon]="faSearch"></fa-icon>',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
faSearch = faSearch;
constructor() {}
}
The problem I am facing is not knowing how I would add the attribute [icon]
to the <fa-icon>
element.
I have tried creating the <fa-icon>
element like this:
const icon = document.createElement('fa-icon');
However, I don't know how I would add the [icon]
attribute. It needs to be bound to the faSearch
variable so it can be rendered.
Here is what I have so far:
import {Directive, ElementRef, Renderer2} from '@angular/core';
import {faSearch} from '@fortawesome/free-solid-svg-icons/faSearch';
@Directive({
selector: '[search-icon]'
})
export class SearchDirective {
constructor(private renderer: Renderer2, private elRef: ElementRef) {
const icon = document.createElement('fa-icon');
renderer.setAttribute(icon, '[icon]', 'faSearch');
renderer.insertBefore(elRef.nativeElement.parentNode, icon, elRef.nativeElement);
}
}
I expect this to bind the faSearch
variable to the [icon]
attribute, but I get this console error:
InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': '[icon]' is not a valid attribute name
Any help would be appreciated.
Edit
The accepted answer actually made me think of doing this differently, which is why i accepted it. I ended up importing font-awesome in my index.html file and just created an i
tag where I set the class based on the icon I needed.
I don't know how applicable this is for you, but the way I have been doing it is like this
<mat-form-field>
<button mat-icon-button>
<mat-icon mat-icon-button
matPrefix>filter_list</mat-icon>
</button>
<input type="text"
[(ngModel)]="value"/>
<button mat-icon-button matSuffix>
<mat-icon matSuffix (click)="myFunction()">close</mat-icon>
</button>
</mat-form-field>
Note the that mat-prefix
and mat-suffix
are needed for left/right alignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With