如何将一个组件作为输入传递给另一个组件?

How to pass a component as input to another component?

我正在使用 ngx-bootstraps 模态组件,我想动态地传递它的组件来显示。我不知道该怎么做。

我使用以下示例,组件作为内容: https://ng-bootstrap.github.io/#/components/modal/examples

我不能用@Input() 传递它,因为它不是变量的实例。

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() {
  }

}

上面的示例有效,但是,我很难引用 'ActualContentComponent'。我宁愿避免一个巨大的开关来查看实际打开的组件(通过传入组件的名称)。

编辑: 我发现我实际上可以使用 @Input()

传递组件
 @Input()
 public component;

 constructor(private modalService: NgbModal) {}

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

根据某些搜索结果,我假设这是不可能的。我想知道我应该为组件使用什么数据类型。

编辑 2:我想根据 https://angular.io/api/core/Type

输入

也许你可以在open方法中传递组件类型?:

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