Search code examples
angularangular-componentsngx-bootstrap

How to pass a component as input to another component?


I'm using ngx-bootstraps modal component, and I want to dynamically pass its components to display. I'm not sure how to do this.

I'm using the following example, components as content: https://ng-bootstrap.github.io/#/components/modal/examples

I can't pass it with @Input() since it's not an instance of a variable.

import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ActualContentComponent} from 'path/path/path';

//TODO: Fix hard important of a component
@Component({
  selector: 'srd-modal',
  templateUrl: './srd-modal.component.html',
  styleUrls: ['./srd-modal.component.css']
})
export class SharedModalComponent implements OnInit {

  constructor(private modalService: NgbModal) {}

  open() {
    const modalRef = this.modalService.open(ActualContentComponent);
    modalRef.componentInstance.name = 'content';
  }

  ngOnInit() {
  }

}

The above example works, however, I have a hard reference to the 'ActualContentComponent'. I'd prefer to avoid a giant switch to see what component to actually open (by passing in the name of the component).

EDIT: I found out I can actually pass the component with @Input()

 @Input()
 public component;

 constructor(private modalService: NgbModal) {}

 open() {
    const modalRef = this.modalService.open(this.component);
    modalRef.componentInstance.name = this.buttonTitle;
  }

I was under the assumption that this wouldn't be possible according to some search results. I was wondering what data-type I should use for component though.

EDIT 2: I guess Type according to https://angular.io/api/core/Type


Solution

  • Maybe you can pass the component type in the open method ?:

        open(component: Type) {
             const modalRef = this.modalService.open(type);
             modalRef.componentInstance.name = 'content';
        }