如何使用使用绑定属性的指令将一个元素附加到另一个元素?

时间:2019-01-10 18:45:17

标签: angular

我正在Angular 7中创建一个指令,该指令将在输入中放置一个放大镜图标。我希望它像这样工作:

<input type="text" search-icon />

我当前正在使用超棒的字体。要使用超棒的图标,您可以将图标导入组件,然后将该图标用作icon标记中的属性:

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() {}
}

我面临的问题是不知道如何将属性[icon]添加到<fa-icon>元素。

我尝试过这样创建<fa-icon>元素:

const icon = document.createElement('fa-icon');

但是,我不知道如何添加[icon]属性。它需要绑定到faSearch变量,以便可以呈现它。

这是我到目前为止所拥有的:

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);
    }

}

我希望这会将faSearch变量绑定到[icon]属性,但出现此控制台错误:

InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': '[icon]' is not a valid attribute name

任何帮助将不胜感激。

修改

被接受的答案实际上使我想到了不同的方式,这就是为什么我接受了它。我最终在我的index.html文件中导入了font-awesome,并且刚刚创建了一个i标记,在该标记中,根据需要的图标设置了类。

1 个答案:

答案 0 :(得分:1)

我不知道这对您有多大适用性,但是我一直这样做的方式是这样的

<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>

请注意,左右对齐需要mat-prefixmat-suffix

相关问题