利用iconName研究了方舟图标的动态加载问题。但代码不起作用。原因何在?什么是最佳做法?以及为什么我需要在指令ngOnChanges()钩子中调用ngOnInit()?我在浏览器中遇到的错误是"FontAwesome:未能找到图标。看起来您为这个组件提供了一个空的或未定义的图标对象。“
import { AppComponent } from './app.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { library, dom } from '@fortawesome/fontawesome-svg-core';
import { fas,faCheck, faCalendar, faTimes } from '@fortawesome/free-solid-svg-icons';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { IconDirective } from './icon.directive';
@NgModule({
declarations: [AppComponent, IconDirective],
imports: [BrowserModule, FontAwesomeModule],
providers: [],
bootstrap: [AppComponent],
entryComponents: [FaIconComponent],
})
export class AppModule {
constructor() {
library.add(fas,faCheck, faCalendar, faTimes);
dom.watch();
}
}import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<div iconDirective></div>'
})
export class AppComponent {
constructor() { }
}import { Directive, OnInit, ViewContainerRef, ComponentFactoryResolver }
from '@angular/core';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { faCheck, faCalendar, faTimes } from '@fortawesome/free-solid-svg-icons';
import { icon } from '@fortawesome/fontawesome-svg-core';
@Directive({
selector: '[iconDirective]'
})
export class IconDirective{
constructor(
public viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
const componentFactory =
this.componentFactoryResolver.resolveComponentFactory(FaIconComponent);
const componentRef =
this.viewContainerRef.createComponent(componentFactory);
(<FaIconComponent>componentRef.instance).icon =
icon({iconName: 'times', prefix: 'fas'});
// (<FaIconComponent>componentRef.instance).iconProp = faCheck; //works
(<FaIconComponent>componentRef.instance).ngOnChanges({});
}
}发布于 2019-08-23 22:56:07
由于0.5.0发行版,angular-fontawesome对动态呈现图标组件有更好的支持。查看正式文件
@Component({
selector: 'fa-host',
template: '<ng-container #host></ng-container>'
})
class HostComponent {
@ViewChild('host', {static: true, read: ViewContainerRef}) container: ViewContainerRef;
constructor(private cfr: ComponentFactoryResolver) {
}
createIcon() {
const factory = this.cfr.resolveComponentFactory(FaIconComponent);
const componentRef = this.container.createComponent(factory);
componentRef.instance.icon = faUser;
// Note that FaIconComponent.render() should be called to update the
// rendered SVG after setting/updating component inputs.
componentRef.instance.render();
}
}原因何在?我在浏览器中遇到的错误是"FontAwesome:未能找到图标。看起来您为这个组件提供了一个空的或未定义的图标对象。“
因为您应该设置iconProp输入属性,而不是icon属性,这是在组件上错误地公开的。请注意,在>0.5.0中不再是这种情况(参见上面的示例)。
什么是最佳做法?
见上面的例子。
以及为什么我需要在指令ngOnChanges()钩子中调用ngOnInit()?
因为图标呈现是通过调用钩子触发的,在模板中添加组件时由角度框架执行。当动态创建组件时,角不调用此钩子,因此需要手动执行。注意,在>0.5.0中有一个专门的方法,它不依赖于这个实现细节就触发呈现-- FaIconComponent.render()。
https://stackoverflow.com/questions/57165261
复制相似问题