【问题标题】:How to pass a component as input to another component?如何将一个组件作为输入传递给另一个组件?
【发布时间】:2019-04-12 09:46:03
【问题描述】:

我正在使用 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:我猜 Type 根据https://angular.io/api/core/Type

【问题讨论】:

    标签: angular angular-components ngx-bootstrap


    【解决方案1】:

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

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

    【讨论】:

    • 我会接受这个作为答案,因为这个解决方案也应该有效。
    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多