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

时间:2019-04-12 09:46:04

标签: angular angular-components ngx-bootstrap

我正在使用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键入

1 个答案:

答案 0 :(得分:0)

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

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