'ng-content not displayed correctly inside a custom modal
Im building a custom modal that will be opened on a button click event. The modal is working okay but when trying to implemenet some content inside it its not displayed corrrectly.
<div class="modal-container">
<button (click)="openModal()">Open me</button>
<div #modal>
<h2>content here</h2>
</div>
</div>
@ViewChild('modal', { read: ViewContainerRef })
entry!: ViewContainerRef;
sub!: Subscription;
openModal() {
this.sub = this.modalService
.openModal(this.entry, 'Are you sure ?', 'click confirm or close')
.subscribe((v: any) => {
});
}
The modal
<div class="some-modal">
<ng-content></ng-content>
</div>
<!-- begin snippet: js hide: false console: true babel: false -->
The result is shown as below.
Solution 1:[1]
<ng-content> it's used when you has a "component". So I imagine you has in your "parent" some like
<button (click)="openModal(modal)">Open me</button>
<app-modal #modal>Content here<<app-modal>
openModal(modal:ModalComponent){
modal.show()
}
<ng-template>it's used in your component and not showed in the app, but you can refer to this and showed by code or by condition (*)
<button (click)="openModal(mytemplate)">Open me</button>
<ng-template #mytemplate>Content here<ng-template>
constructor(private viewContainerRef:ViewContainerRef){}
openModal(mytemplate:TemplateRef<any>){
this.viewContainerRef.createEmbeddedView(mytemplate);
}
(*)I don't know about your code. Insead use viewContainerRef you can use cdk-overlay or use a variable
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eliseo |

