我在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
标签,在其中我根据需要的图标设置了类。
我不知道这对您有多大适用性,但是我一直在这样做
<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-prefix
并且mat-suffix
是左/右对齐所必需的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句