Search code examples
angularangular2-changedetection

Action Detection on dynamically created component


I am creating a dynamically created component in angular 4 as shown below.

    import {
  Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
  ViewContainerRef
} from '@angular/core';


@Component({
  selector: 'my-app',
  template: `
      <h1>Hello {{name}}</h1>
      <ng-container #vc></ng-container>
  `
})
export class AppComponent {
  @ViewChild('vc', {read: ViewContainerRef}) vc;
  name = `Angular! v${VERSION.full}`;

  constructor(private _compiler: Compiler,
              private _injector: Injector,
              private _m: NgModuleRef<any>) {
  }

  ngAfterViewInit() {
    const tmpCmp = Component({
        moduleId: module.id, templateUrl: './e.component.html'})(class {
    });
    const tmpModule = NgModule({declarations: [tmpCmp]})(class {
    });

    this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
      .then((factories) => {
        const f = factories.componentFactories[0];
        const cmpRef = f.create(this._injector, [], null, this._m);
        cmpRef.instance.name = 'dynamic';
        this.vc.insert(cmpRef.hostView);
      })
  }
}

I want to trigger an action from the template url as shown below:Where and how do I handle this click event. e.component.html

<div>
  <button  (click)="action()"></button>
  <h1 (click)="action()">Phrase</h1>  
</div>

Solution

  • You need to create method in your dynamic component class.

    const tmpCmp = Component({moduleId: module.id, templateUrl: './e.component.html'})(class {
    
                     action(){
                         console.log('Action button clicked');
                     }
    
                   });