有没有办法使用Angular将组件成员中的字符串转换为组件HTML中的动态属性?
export class ContextualMenuComponent implements OnInit {
directive: string;
constructor() { }
ngOnInit() {
this.directive = "mat-mini-fab";
}
然后在html中就像这样
<button [directive]>click</button>
但我希望它实际上是
<button mat-mini-fab>click</button>
答案 0 :(得分:0)
而不是HTML属性,需要的是动态添加组件,因为在构建时不知道确切的类型。因为Angular不知道将需要哪些组件(因为它们不是静态知道的),所以需要将它们添加到NgModule中的entryComponents
中。您将ComponentFactoryResolver
用于此目的。
下面,AdItem
是要注入的组件类型。它们不是由选择器注入的,而是由课程注入的。
export class AdBannerComponent implements AfterViewInit, OnDestroy {
@Input() ads: AdItem[];
currentAddIndex: number = -1;
@ViewChild(AdDirective) adHost: AdDirective;
subscription: any;
interval: any;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngAfterViewInit() {
this.loadComponent();
this.getAds();
}
ngOnDestroy() {
clearInterval(this.interval);
}
loadComponent() {
this.currentAddIndex = (this.currentAddIndex + 1) % this.ads.length;
let adItem = this.ads[this.currentAddIndex];
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
let viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
(<AdComponent>componentRef.instance).data = adItem.data;
}
getAds() {
this.interval = setInterval(() => {
this.loadComponent();
}, 3000);
}
}
来源:https://angular.io/guide/dynamic-component-loader#loading-components