Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I append an element to another element using a directive that uses binding attributes?

Tags:

angular

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.

like image 550
alpa_chino Avatar asked Oct 28 '22 21:10

alpa_chino


1 Answers

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.

like image 156
rhavelka Avatar answered Jan 02 '23 21:01

rhavelka