Reputation: 14922
I originally had an ng-bootstrap (5.1.4) modal and the button that opens it inline in my page template, like this:
<ng-template #basicMessage
let-modal>
<div class="modal-header">
<h2 id="modal-basic-title"
class="modal-title">Modal headline</h2>
<button type="button"
class="close"
aria-label="Close"
(click)="modal.dismiss('Close icon clicked')">
<span aria-hidden="true"></span>
</button>
</div>
<div class="modal-body">
<p>Lorem ipsum dolor sit amet, duo ei volumus perfecto ocurreret, nam et volutpat explicari hendrerit.</p>
</div>
</ng-template>
<button class="btn btn-primary mb-3"
(click)="open(basicMessage, { ariaLabelledBy: 'modal-basic-title' })"
matRipple>
View Demo
</button>
This page has several of these modal demos, each with a different template tag, such as #singleChoiceActionModal
and #basicMessage
.
Now I would like to move each modal into its own component, and call the modal from the viewdemo button, passing the name of which demo to open. Problem is, once I move the above modal ng-template into its own component:
import { Component } from '@angular/core';
@Component({
selector: 'app-ngmodal-basic',
template: `
<ng-template #basicMessage let-modal>
<div class="modal-header">
<h2 id="modal-basic-title" class="modal-title">Modal headline</h2>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Close icon clicked')">
<span aria-hidden="true"></span>
</button>
</div>
<div class="modal-body">
<p>
Lorem ipsum dolor sit amet, duo ei volumus perfecto ocurreret, nam et volutpat explicari hendrerit.
</p>
</div>
</ng-template>
`,
styles: []
})
export class NgmodalBasicComponent {}
and then add this component to my demo page as in
<app-ngmodal-basic></app-ngmodal-basic>
<button class="btn btn-primary mb-3"
(click)="open(basicMessage, { ariaLabelledBy: 'modal-basic-title' })"
matRipple>
View Demo
</button>
the backdrop pops up but no modal.
Since this is a bit confusing, I made a Stackblitz: https://stackblitz.com/edit/angular-rvsxpz
Upvotes: 0
Views: 1959
Reputation: 27409
You have to pass Template reference to a first argument of open method. But in your example your are passing undefined that's why It's not working. You have to get app-ngmodal-basic template reference first then pass that ref to open method. To get app-ngmodal-basic template reference use ViewChild, Then add template variable on app-ngmodal-basic to get access
Try this
ng-model-basic.component.ts
export class NgmodalBasicComponent {
@ViewChild("basicMessage", { static: false })
public basicMessage: TemplateRef<any>;
constructor() {}
}
hello.component.html
<app-ngmodal-basic #modal></app-ngmodal-basic>
<button class="btn btn-primary my-5 d-block"
(click)="open(modal.basicMessage, { ariaLabelledBy: 'modal-basic-title' })"
matRipple>
Open Basic Message Modal
</button>
Upvotes: 1