【问题标题】:Pass component dinamically to another, generic component?将组件动态传递给另一个通用组件?
【发布时间】:2019-06-14 07:47:06
【问题描述】:

使用 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 中所需的位置

【问题讨论】:

    标签: javascript html angular typescript bootstrap-modal


    【解决方案1】:

    您可以在角度模板中使用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>
    

    【讨论】:

    • 它已经以另一种方式调用: const modalRef = this.modalService.open(NgbdModalComponent);我不能使用 ng-content
    • 如果是变量可以使用innerHtml。这就是你要找的吗?
    • 我不能使用innerHTML
    • 也许您需要像这样的第 3 方模态库 npmjs.com/package/ngx-smart-modal
    • 这不是一个选项
    猜你喜欢
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多