Reputation: 1060
I have a component where I am dynamically injecting another component. Please refer the code shown below:
getID() {
const componentRef = this.componentFactoryResolver
.resolveComponentFactory(CodesComponent).create(this.injector);
componentRef.instance.terms = this.terms;
this.appRef.attachView(componentRef.hostView);
const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
$(domElem).insertAfter($(event.target).closest('tr'));
}
Also there is a function in my component:
sayHello() {
console.log('hi');
}
And my CodesComponent
looks like below:
<p (click) = "sayHello()"></p>
Now question is how can I call sayHello()
function from dynamically created component?
Upvotes: 1
Views: 1788
Reputation: 10844
For your use case I would recommend using Angulars dependency injection to inject the parent component into your dynamic component.
Here is a working StackBlitz demo for you.
Code in your parent component
import {
Component, ViewChild, AfterContentInit, ComponentFactoryResolver,
Compiler, ViewContainerRef, NgModule, NgModuleRef
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
@ViewChild('vc', { read: ViewContainerRef }) _container: ViewContainerRef;
private cmpRef;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private compiler: Compiler,
private _m: NgModuleRef<any>) { }
ngAfterContentInit() {
this.getID();
}
public sayHello(): void{
alert("Hello!");
}
private getID(): void {
@Component({
template: `<h2>This is a dynamic component</h2>
<p (click)="_parent.sayHello()">Click me!</p>`
})
class DynamicComponent {
constructor(public _parent: AppComponent) { }
}
@NgModule({
imports: [
BrowserModule
],
declarations: [DynamicComponent],
}) class DynamicModule { }
const mod = this.compiler.compileModuleAndAllComponentsSync(DynamicModule);
const factory = mod.componentFactories.find((comp) =>
comp.componentType === DynamicComponent
);
this.cmpRef = this._container.createComponent(factory);
}
}
Upvotes: 3