1

everything is in the title.

I would want to create modals from my regular angular 2 components. The thing is, we need to inject NavParams to retrieve arguments and NavController to close the modal.

Thanks

edit: I have posted an answer but maybe there is something better. Thanks again.

chikincrow
  • 393
  • 3
  • 11

1 Answers1

0

One possible solution is to create a generic wrapper as modal that will instantiate the reel component.

I used this link: Is it possible to manually instantiate component in angular 2

Here is my code to create the modal:

    let modal = this.modalController.create(ModalWrapper, {
      type: MyAngular2SimpleComponent,
      init: function (component) {
        component.input1 = argument1;
        component.input2 = argument2;
      }
    });
    modal.onDidDismiss(data => {
      console.log(data);
    });
    modal.present();

My angular component:

@Component({
    template: `{{input1}} and {{input2}}`
})
export class MyAngular2SimpleComponent {
    @Input() input1;
    @Input() input2;
}

The modal wrapper:

@Component({
  template: `
    <div #target></div>
  `
})
export class ModalWrapper {

  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;

  componentRef:ComponentRef<any>;
  private isViewInitialized:boolean = false;

  constructor(private resolver:ComponentResolver, private params:NavParams) {
    this.type = params.get('type');
  }

  ngOnInit() {

  }

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.componentRef) {
      this.componentRef.destroy();
    }
    this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.componentRef = this.target.createComponent(factory);

      // to access the created instance use
      // this.compRef.instance.someProperty = 'someValue';
      // this.compRef.instance.someOutput.subscribe(val => doSomething());
      this.params.get('init')(this.componentRef.instance);
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();
  }

  ngOnDestroy() {
    if(this.componentRef) {
      this.componentRef.destroy();
    }
  }
}

The main thing in the wrapper is:

this.params.get('init')(this.componentRef.instance);

I call the init method that i passed in parameter when I created the modal. Some kind of double dispatch that allows populating the data.

Thanks to Günter Zöchbauer

Community
  • 1
  • 1
chikincrow
  • 393
  • 3
  • 11