I'm using Angular 11 and I'm going to detect if my component has any child element with [footer]
attribute; then if there is no child element with that selector, I will not show modal-footer.
bs-modal.component.html:
<div class="modal fade" id="{{id}}">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-content select="[header]"></ng-content>
</div>
<div class="modal-body">
<ng-content select="[body]"></ng-content>
</div>
<div class="modal-footer">
<ng-content select="[footer]"></ng-content>
</div>
</div>
</div>
</div>
app.component.html:
<app-bs-modal [id]="'user-upsert-modal'">
<div header>
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
</button>
</div>
<div body>
...
</div>
<!-- FOOTER IS HERE OR NOT -->
<div footer>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</app-bs-modal>
Now when I remove <div footer>...</div>
from app.component.ts, there is still a <div class="modal-footer">...</div>
, because only the content is not applied.
So, how to check if is not applied, to remove modal-footer element by something like *ngIf?
Try something like this:
// add modalFooter reference variable here
<div #modalFooter class="modal-footer" *ngIf="displayFooter">
<ng-content select="[footer]"></ng-content>
</div>
bs-modal.component.ts:
export class BSModalComponent implements AfterViewInit {
@ViewChild('modalFooter', { static: false }) modalFooter: ElementRef;
// set displayFooter to true so the *ngIf is true and we can then decide
// to hide or show it
displayFooter = true;
ngAfterViewInit() {
// if the modal footer does not have any child nodes, make displayFooter false
setTimeout(() => {
if (this.modalFooter.nativeElement.children.length === 0) {
this.displayFooter = false;
}
});
}
}