Search code examples
angularangular-bootstrap

what is content (reference) content: TemplateRef<any> in angular?


Hello I'm staring to work with Angular, when I was adding a modal with bootstrap into my html I found I need to send the parameter content which I never declarete

<tbody *ngIf="!loading">
        <tr
          (click)="openModal(content,note)"
          *ngFor="let note of notesAndCommentsContainer"
        >
          <td>{{ note.author }}</td>
          <td>{{ note.preview }}</td>
          <td>{{ note.property }}</td>
          <td>{{ note.date }}</td>
        </tr>
      </tbody>

and get in the typescript the next

openModal(content:object,note:object) {
    this.modalTitle = note['author'];
    this.modalDate = note['date'];
    this.modalBody = note['comment'];
    this.commentProperty = note['property'];
    this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'})    
  }

this is something curious and I want to know how to generate this object from typescript because it is necessary to launch a bootstrap modal in angular I'm using Angular 12.2.3


Solution

  • Content can be provided as a TemplateRef or a component type.

    So you can create a new component and pass it to the function:

    this.modalService.open(YourModalComponent, yourOptions)
    

    not passing the content from your template (so only openModal(note)) or you can declare a template inside your component:

    <ng-template #yourModalTemplate let-modal>
    ...
    </ng-template>
    

    Passing it thanks to the reference #yourModalTemplate (you can give it the name you like)

    <tr (click)="openModal(yourModalTemplate,note)" ...>
    

    If you pass a component type as content, then instances of those components can be injected with an instance of the NgbActiveModal class. You can then use NgbActiveModal methods to close / dismiss modals from "inside" of your component.

    Some useful links: