我有一个函数,用于将组件从有角度的核心应用程序导入所有库。 此函数将组件作为dom元素返回,并且我将其附加到子库中。 现在我想获得组件,但要给它一些输入。
这是我正在使用的代码。我没有收到任何错误,但是没有看到input属性。
将组件作为dom元素返回的函数
getComponent(componentInput?: string): HTMLElement {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(SharedcomponentComponent);
const componentRef = componentFactory.create(this.injector);
//Injecting Inputs to the component instance
if(componentInput != undefined){
componentRef.instance.someProp = componentInput;
}
this.appRef.attachView(componentRef.hostView);
const domElem = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
return domElem;
}
我的组件
@Component({
selector: 'app-sharedcomponent',
templateUrl: './sharedcomponent.component.html',
styleUrls: ['./sharedcomponent.component.css']
})
export class SharedcomponentComponent implements OnInit {
@Input('someProp') someProp: string;
constructor() { }
ngOnInit() {
}
clickMe(){
alert("I am the core component :)");
}
}
我的组件HTML
<button (click)="clickMe()">
Click Me :)
</button>
<br/>
<p>
Hello there {{someProp}}
</p>
答案 0 :(得分:0)
我找到了解决方案。 下面的代码现在可以正常工作了
getComponent(componentInput?: string): HTMLElement {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(SharedcomponentComponent);
const componentRef = componentFactory.create(this.injector);
//Injecting Inputs to the component instance
if(componentInput != undefined){
let inputs = { someProp: componentInput };
Object.keys(inputs).map(input => {
componentRef.instance[input] = inputs[input];
});
}
this.appRef.attachView(componentRef.hostView);
const domElem = (componentRef.hostView as EmbeddedViewRef<SharedcomponentComponent>).rootNodes[0] as HTMLElement;
return domElem;
}