我有类似的要求并使用了ComponentFactoryResolver。但是,我在 ng-template 周围放置了一个包装器,如下所示:
@Component({
selector: 'tn-dynamic',
template: `<ng-template #container></ng-template>`,
providers: [SubscriptionManagerService],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DynamicComponent<T>
extends DynamicComponentBase<T, T, ComponentData>
implements OnChanges, OnDestroy {
@Input()
set componentData(data: ComponentData) {
if (!data) {
return;
}
try {
let type: Type<T> = getComponentType(data.type);
this._factory = this.resolver.resolveComponentFactory(type);
let injector = Injector.create([], this.vcRef.parentInjector);
this._factoryComponent = this.container.createComponent(this._factory, 0, injector);
this._currentComponent = this._factoryComponent.instance;
this._factoryComponent.location.nativeElement.classList.add('tn-dynamic-child');
} catch (er) {
console.error(`The type ${data.type.library}
.${data.type.key} has not been registered. Check entryComponents?`);
throw er;
}
}
// Handle ngOnChanges, ngOnDestroy
}
然后我将循环放在我的组件<tn-dynamic [componentData]="myComponentData">
您的 componentData 包含控件的类型,因此您将拥有另一个服务,该服务将根据请求的类型返回正确的类型。
当您开始使用解析器时,不会分配您的输入/输出。所以你必须自己处理。
ngOnChanges(changes: SimpleChanges) {
let propertyWatch = this.getPropertyWatch();
for (let change in changes) {
if (change === propertyWatch) {
let data = this.getComponentData(changes[change].currentValue);
if (data) {
if (data.inputs) {
this.assignInputs(data.inputs);
}
if (data.outputs) {
this.assignOutputs(data.outputs);
}
if (this.implementsOnChanges()) {
let dynamiChanges = DynamicChanges.create(data);
if (dynamiChanges) {
(<OnChanges><any>this._currentComponent).ngOnChanges(dynamiChanges);
}
}
}
}
}
}
private unassignVariables() {
if (this.factory && this.factory.inputs) {
for (let d of this.factory.inputs) {
this._currentComponent[d.propName] = null;
}
}
}
protected assignInputs(inputs: ComponentInput) {
for (let key in inputs) {
if (inputs[key] !== undefined) {
this._currentComponent[key] = inputs[key];
}
}
}
private assignOutputs(outputs: ComponentOutput) {
for (let key in outputs) {
if (outputs[key] !== undefined) {
let eventEmitter: EventEmitter<any> = this._currentComponent[key];
let subscription = eventEmitter.subscribe(m => outputs[key](m));
this.sm.add(subscription);
}
}
}
然后,我发现使用formControl 而不是ngModel 处理我的表单输入更好。尤其是在处理验证器时。如果您继续使用ngModel,您将无法轻松添加/删除验证器。但是,创建一个带有[formControl] 的动态组件附加到使用ComponentFactoryResolver 生成的控件似乎是不可能的。所以我不得不即时编译模板。所以我用另一个看起来像这样的服务创建了一个控件:
const COMPONENT_NAME = 'component';
@Injectable()
export class RuntimeComponent {
constructor(
private compiler: Compiler,
@Optional() @Inject(DEFAULT_IMPORTS_TOKEN)
protected defaultImports: DefaultImports
) {
}
protected createNewComponent(tmpl: string, args: any[]): Type<any> {
@Component({
selector: 'tn-runtime-component',
template: tmpl,
})
class CustomDynamicComponent<T> implements AfterViewInit, DynamicComponentData<T> {
@ViewChild(COMPONENT_NAME)
component: T;
constructor(
private cd: ChangeDetectorRef
) { }
ngAfterViewInit() {
this.cd.detectChanges();
}
}
Object.defineProperty(CustomDynamicComponent.prototype, 'args', {
get: function () {
return args;
}
});
// a component for this particular template
return CustomDynamicComponent;
}
protected createComponentModule(componentType: any) {
let imports = [
CommonModule,
FormsModule,
ReactiveFormsModule
];
if (this.defaultImports && this.defaultImports.imports) {
imports.push(...this.defaultImports.imports);
}
@NgModule({
imports: imports,
declarations: [
componentType
],
})
class RuntimeComponentModule {
}
// a module for just this Type
return RuntimeComponentModule;
}
public createComponentFactoryFromStringSync(template: string, attributeValues?: any[]) {
let type = this.createNewComponent(template, attributeValues);
let module = this.createComponentModule(type);
let mwcf = this.compiler.compileModuleAndAllComponentsSync(module);
return mwcf.componentFactories.find(m => m.componentType === type);
}
public createComponentFactoryFromMetadataSync(selector: string, attributes: { [attribute: string]: any }) {
let keys = Object.keys(attributes);
let attributeValues = Object.values(attributes);
let attributeString = keys.map((attribute, index) => {
let isValueAFunctionAsString = typeof attributeValues[index] === 'function' ? '($event)' : '';
return `${attribute}="args[${index}]${isValueAFunctionAsString}"`;
}).join(' ');
let template = `<${selector} #${COMPONENT_NAME} ${attributeString}></${selector}>`;
return this.createComponentFactoryFromStringSync(template, attributeValues);
}
}
我的代码并不完美,这就是为什么我只给你重要的部分。你必须玩弄这个想法,让它按照你的方式工作。有一天我应该写一篇关于这个的博客文章:)
我查看了您的 plunker,但您在使用 ngFor 时没有正确使用#name。如果您的循环正常工作,您将无法在 TypeScript 中正确获取它。
此外,您不能在 ng 模板上执行 *ngFor=""。所以你的循环只是不工作。见https://toddmotto.com/angular-ngfor-template-element
祝你好运!