EugenSunic
EugenSunic

Reputation: 13703

Pass component dinamically to another, generic component?

Using Angular2+ and would like to pass a content component to the generic modal component.

Component which should pass Content component

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?
  }

Modal component .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();
  }
}

Modal component .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>

What is the best way to achieve it in order to keep the modal window generic?

NOTE:

Upvotes: 1

Views: 334

Answers (1)

Jonas Praem
Jonas Praem

Reputation: 2444

You can pass content to the component by using the ng-content directive in angular templating

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

Then you can call that component with something like:

<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>

Upvotes: 0

Related Questions