https://stackblitz.com/edit/angular-dynamic-component-problem
пожалуйста, посмотрите живую версию. Я надеюсь, что это решение удовлетворит ваши потребности.
app.component.ts
import {
Component,
ViewChild,
ComponentFactoryResolver,
ViewContainerRef,
Type
} from "@angular/core";
import { PlaceholderDirective } from "./placeholder.directive";
import { DatasetAComponent } from "./dataset-a.component";
import { DatasetBComponent } from "./dataset-b.component";
@Component({
selector: "my-app",
templateUrl: "./app.component.html"
})
export class AppComponent {
hostViewContainerRef: ViewContainerRef;
@ViewChild(PlaceholderDirective, { static: false })
datasetHost: PlaceholderDirective;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
onLoadA() {
this.loadNewDataset(DatasetAComponent, "dataset A loaded.");
}
onLoadB() {
this.loadNewDataset(DatasetBComponent, "dataset B loaded.");
}
onClear() {
this.hostViewContainerRef.clear();
}
loadNewDataset(
datasetComponent: Type<DatasetAComponent> | Type<DatasetBComponent>,
message: string
) {
const datasetCmpFactory = this.componentFactoryResolver.resolveComponentFactory(
datasetComponent
);
this.hostViewContainerRef = this.datasetHost.viewContainerRef;
this.hostViewContainerRef.clear();
const componentRef = this.hostViewContainerRef.createComponent(
datasetCmpFactory
);
componentRef.instance.message = message;
}
}
набор данных-a.component.ts
import { Component, Input } from "@angular/core";
import colors from "./data/a.json";
@Component({
templateUrl: "./dataset-a.component.html"
})
export class DatasetAComponent {
@Input() message: string;
dataset = colors;
}
app.module.ts
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
import { PlaceholderDirective } from "./placeholder.directive";
import { DatasetAComponent } from "./dataset-a.component";
import { DatasetBComponent } from "./dataset-b.component";
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [
AppComponent,
PlaceholderDirective,
DatasetAComponent,
DatasetBComponent
],
bootstrap: [AppComponent],
entryComponents: [DatasetAComponent, DatasetBComponent]
})
export class AppModule {}
app.component. html
<h1>using view container ref</h1>
<button (click)="onLoadA()">Dataset A</button> |
<button (click)="onLoadB()">Dataset B</button> |
<button (click)="onClear()">Clear View</button>
<br />
<ng-template appPlaceholder></ng-template>