<dynamic-component>
内的组件,但也有ngfor,所以在我得到几个<dynamic-component>
后,如何只指定一个地方来添加这个组件?任何帮助,谁了解我的问题。
<div *ngFor="let Mytask of tasks">
<thead></thead>
<tbody>
<tr *ngIf="!Mytask.ParentTaskId"(click)="setParentTask(new,Mytask)"
(dblclick)="showEditForTask(Mytask)">
<td>{{Mytask.Title}}</td>
<td>{{Mytask.StartTime}}</td>
<td>{{Mytask.FinishTime}}</td>
<td>{{Mytask.States.State}}</td>
<td> <button (click)="createTaskComponent(Mytask)">Create</button><td>
</tr>
<tr #new>
<dynamic-component [componentData]="componentData"></dynamic-component>
</tr>
</tbody>
</div>
我的组件中的功能
componentData:any = null;
createTaskComponent(task:Tasks){
this.getMyChildren(task);
this.componentData = {
component: TaskWorldComponent,
inputs: {
tasks: this.children
}
};
}
插入组件的代码来自plunker
import {Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector,
ComponentFactoryResolver} from '@angular/core';
import TaskWorldComponent from './task-world-component';
@Component({
selector: 'dynamic-component',
entryComponents: [TaskWorldComponent],
template: `
<div #dynamicComponentContainer></div>
`,
})
export default class DynamicComponent {
currentComponent:any = null;
@ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
@Input() set componentData(data: {component: any, inputs: any }) {
if (!data) {
return;
}
let inputProviders = Object.keys(data.inputs).map((inputName) => {return {provide: inputName, useValue: data.inputs[inputName]};});
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector);
let factory = this.resolver.resolveComponentFactory(data.component);
let component = factory.create(injector);
this.dynamicComponentContainer.insert(component.hostView);
if (this.currentComponent) {
this.currentComponent.destroy();
}
this.currentComponent = component;
}
constructor(private resolver: ComponentFactoryResolver) {
}
}
和要添加的组件
import {Component, Injector} from '@angular/core';
import { AspNetUsers,Projects,AspNetRoles,AspNetUserClaims,AspNetUserLogins,Tasks,States} from './shared/classes';
@Component({
selector: 'task-world',
template: `
<div *ngFor="let Mytask of tasks">
<thead></thead>
<tbody>
<tr>
<td>{{Mytask.Title}}</td>
<td>{{Mytask.StartTime}}</td>
<td>{{Mytask.FinishTime}}</td>
<td>{{Mytask.States.State}}</td>
</tr>
</tbody>
</div>
<button (click)="createTaskComponent()">Create Task</button>
<dynamic-component [componentData]="componentData"></dynamic-component>
`,
})
export default class TaskWorldComponent {
tasks:Tasks[] = [];
constructor(private injector: Injector) {
this.tasks = this.injector.get('tasks');
}
}