将组件灵巧地传递给另一个通用组件?

时间:2019-01-20 21:31:04

标签: javascript html angular typescript bootstrap-modal

使用 Angular2 + ,并希望将内容组件传递给通用模式组件。

应通过内容组件的组件

openModal() {
    // open modal component
    const modalRef = this.modalService.open(NgbdModalComponent);

    // attach variable values and functions
    modalRef.componentInstance.name = this.name;
    modalRef.componentInstance.content = this.content;
    modalRef.componentInstance.buttonName = this.buttonName;
    modalRef.componentInstance.buttonClass = this.buttonClass;
    modalRef.componentInstance.onConfirm = () => this.onConfirm();
    modalRef.componentInstance.onClose = () => this.onClose();
    // pass content component dinamically?
  }

模态组件.ts

export class NgbdModalComponent {
  name: string;
  content: string;
  buttonName: string;
  buttonClass: string;

  onConfirm: () => void;
  onClose: () => void;

  constructor(public activeModal: NgbActiveModal) {}

  confirm(): void {
    this.onConfirm();
  }

  close(): void {
    this.onClose();
  }
}

模态组件.html

<div class="modal-header">
  <h4 class="modal-title">{{name}}</h4>
  <button type="button" class="close" aria-label="Close" (click)="close()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
 **Component shoud land here**
</div>
<div class="modal-footer">
  <button type="button" [class]="buttonClass" (click)="confirm()">
    <span>{{buttonName}}</span>
  </button>
</div>

为了保持模式窗口的通用性,实现它的最佳方法是什么?

注意:

  • 我不能使用不能用于组件插入的innerHTML
  • 我无法使用ng-content,因为我没有将模式窗口称为 组件,而是使用const modalRef =动态实例化它 this.modalService.open(NgbdModalComponent);
  • 不应该使用第三方库
  • 我想重用modalRef.componentInstance将组件附加到modal.html中的所需位置

1 个答案:

答案 0 :(得分:0)

您可以通过在角度模板中使用ng-content指令将内容传递给组件

<div class=”modal-body”>
  <ng-content></ng-content>
</div>

然后,您可以使用以下方式调用该组件:

<my-modal-window title=”My custom title”>
      This content comes from the parent component. 
      I want to add some <b>HTML content</b>
      into it with dynamic expressions to display the {{name}}
      of the current user.
</my-modal-window>