Я собираюсь разрешить компоненты динамически для разных операторов.
Итак, я создал одну директиву и один компонент для нее.
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[mcmsDynamicHost]'
})
export class DynamicHostDirective {
constructor(
public viewContainerRef: ViewContainerRef
) { }
}
import { AfterViewInit, Component, ComponentFactoryResolver, Input, ViewChild } from '@angular/core';
import { DynamicHostDirective } from '@mcms/ui-kit/dynamic-host/dynamic-host.directive';
@Component({
selector: 'mcms-dynamic-host',
templateUrl: './dynamic-host.component.html',
styleUrls: ['./dynamic-host.component.scss']
})
export class DynamicHostComponent implements AfterViewInit {
@ViewChild(DynamicHostDirective) dynamicHost: DynamicHostDirective;
@Input() component;
constructor(
private componentFactoryResolver: ComponentFactoryResolver
) { }
ngAfterViewInit(): void {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.component);
const viewContainerRef = this.dynamicHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
}
}
// component template
<ng-template mcmsDynamicHost></ng-template>
Теперь я используя их таким образом.
<div *ngFor="let item of dashboard">
<mcms-dynamic-host [component]="item.card"></mcms-dynamic-host>
</div>
this.dashboard = [
{cols: 2, rows: 3, y: 0, x: 0, dragEnabled: true, card: WelcomeCardComponent, title: 'Welcome to Municipal CMS!'},
{cols: 1, rows: 3, y: 0, x: 2, dragEnabled: true, card: SiteResumeCardComponent, title: 'Site Resume'},
{cols: 2, rows: 5, y: 3, x: 0, dragEnabled: true, card: TrafficActivityCardComponent, title: 'Traffic activity'},
];
Stati c компоненты отображаются без каких-либо проблем, которые работают. Но если я попытаюсь связать некоторые значения с шаблоном внутри динамически разрешенных компонентов, например * ngFor или даже * ngIf, все ошибки сгенерируются - ExpressionChangedAfterItHasBeenCheckedError
Но когда я сделал этот трюк,
ngOnInit(): void {
setTimeout(() => {
this.data = [
{ image: 'assets/images/green-icons/page-small.svg', title: 'Pages', count: 5 },
{ image: 'assets/images/green-icons/user-small.svg', title: 'Active Users', count: 7 },
{ image: 'assets/images/green-icons/blog-small.svg', title: 'Blog Post', count: 12, pending: 3 },
{ image: 'assets/images/green-icons/comment-small.svg', title: 'Comments', count: 54, pending: 8 },
{ image: 'assets/images/green-icons/media-small.svg', title: 'Digital Assets', count: 230 },
];
}, 100);
}
ошибок нет. Это немного странно для меня, в любом случае мы можем go с этим справиться, но когда я пытаюсь использовать, например, компонент @ angular / material, нет способа сделать этот трюк.
Кто-нибудь сталкивался с подобной проблемой?
Здесь идет ссылка на стек - https://stackblitz.com/edit/angular-kf3pdw