Angular 2 dynamic component events

I am trying to create components dynamically, but I want to add a click action to it, and I don't know how to do it. I tried to do this:

constructor(public navCtrl: NavController, private resolver: ComponentFactoryResolver) { this.lastSelectedResource = this.defaultImage; } public createNew() { this.container.detach(0); } ngAfterContentInit() { let widgetFactory = this.resolver.resolveComponentFactory(CreateComponent); let widgetReference = this.container.createComponent(widgetFactory); widgetReference.instance.click = this.createNew; } 

but this is not so. Does anyone know how?

+1
source share
1 answer

You can insert a renderer and use

 this.renderer.listen(widgetReference.location.nativeElement, 'click', (event) => { this.createNew(e);}); 

Similar to Angular2 - catch / subscribe to an event (click) in dynamically added HTML

( widgetReference.location provides ElementRef )

+2
source

Source: https://habr.com/ru/post/1013788/


All Articles