0

I have a modal that is dynamically created from a component, this way:

@Injectable()
export class SharedService {
  showModal:Subject<any> = new Subject();
}

@Component({
  selector: 'comp-comp',
  template: `MyComponent dataToPass: {{dataToPass}}, dataToPass2: {{dataToPass2}}
            <button (click)="doSomethingAndClose()">Do something and close</button>`
})
export class CompComponent {
  private dataToPass2;

  constructor() {}

  ngAfterContentInit() {
    this.dataToPass2 = this.dataToPass + ' hello';
  }

  doSomethingAndClose() {
    this.dataToPass2 = this.dataToPass + ' I'm gonna close;
    console.log(this.dataToPass2);
    this.destroy();
  }
}

export class ModalComponent {
  @ViewChild('theBody', {read: ViewContainerRef}) theBody;

  theHeader: string = '';
  dataToPass: string = '';
  cmpRefBody:ComponentRef<any>;

  constructor(
    sharedService:SharedService, 
    private componentFactoryResolver: ComponentFactoryResolver, 
    injector: Injector) {

    sharedService.showModal.subscribe(data => {
      if(this.cmpRef) {
        this.cmpRef.destroy();
      }
      let factory = this.componentFactoryResolver.resolveComponentFactory(data.type);
      this.cmpRef = this.theBody.createComponent(factory);
      this.cmpRef.instance.dataToPass = data.dataToPass;
      this.dataToPass = data.dataToPass;
      this.theHeader = data.title;
      console.log(data.title);
      console.log(data.dataToPass);
      $('#theModal').modal('show');
    });
  }

  close() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
    this.cmpRef = null;
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello</h2>
      <button (click)="showDialog()">show modal</button>
      <child-component></child-component>
    </div>
  `,
})
export class App {

  constructor(private sharedService:SharedService) {}

  showDialog() {
    this.sharedService.showModal.next({'type': CompComponent, 'title': 'titolo1', 'dataToPass': 'dataToPass'});
  }

}

(referrer: Angular 2 modals shared between components).

Inside modal component there's a close() function which with a this.CmpRef.destroy() closes the modal itself.

As you can see here in my plunk, I would like to make the modal component close from the component loaded dynamically inside the modal one. I tried to do it with the function doSomethingAndClose() but it gives me this error:

VM1882 core.umd.js:3472 EXCEPTION: Cannot set property stack of [object Object] which has only a getter

I have no idea how to do it, because inside dynamically created component I don't have any reference to modal parent component...

Community
  • 1
  • 1
B. Ciervo
  • 135
  • 4
  • 16

0 Answers0