我使用此链接创建一个动态加载组件的指令 - link 我的问题是我需要将组件添加到父组件而不是当前的ViewContainer。有谁知道我怎么能这样做?
背景 - 我在引导模式中动态加载组件。当我的溢出被设置为隐藏时,该组件正在被切断。所以我需要在模态之外使用组件,以便我可以将它放在模态上。
以下是指令的代码
import {
ComponentFactory, ComponentFactoryResolver, ComponentRef,
Directive, ElementRef, EventEmitter,
HostListener, Input, Output, Renderer,
ViewContainerRef
} from '@angular/core';
import { AutoCompleteComponent } from './auto-complete.component';
import { AutoComplete } from './auto-complete.model';
import { Contact } from './contact.model';
@Directive({
selector: '[AutoComplete]'
})
export class AutoCompleteDirective {
autoCompleteComponentRef: ComponentRef<AutoCompleteComponent>;
@Output() onContactSelected = new EventEmitter<Contact>();
constructor(
private el: ElementRef,
private viewContainer: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
private renderer: Renderer
) {
}
@HostListener('keyup') onKeyUp() {
this.search();
}
private search()
{
if (this.autoCompleteComponentRef == undefined) {
let autoCompleteComponentFactory = this.componentFactoryResolver.resolveComponentFactory(AutoCompleteComponent);
this.autoCompleteComponentRef = this.viewContainer.createComponent(autoCompleteComponentFactory);
this.autoCompleteComponentRef.instance.onBusinessContactSelected.subscribe((x) => {
this.onContactSelected.emit(x);
})
}
this.autoCompleteComponentRef.instance.search(this.forename, this.surname);
}
}
答案 0 :(得分:0)
我有同样的困惑,即组件(动态加载)总是在我想用它作为容器或父组件的组件之后添加。这是一个错误或功能设计?