Angular 11:如何检查是否应用了特定的子元素来删除 ng-content 的父元素 div?

Angular 11: how to check if specific child element is applied to remove parent div of ng-content?

我正在使用 Angular 11 并且我将检测我的组件是否有任何具有 [footer] 属性的子元素;那么如果那个选择器没有子元素,我就不会显示 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>

现在当我从app.component.ts中删除<div footer>...</div>时,还有一个<div class="modal-footer">...</div>,因为只有内容没有应用。

那么,如何检查 是否未应用,通过类似 * 的方式删除 modal-footer 元素ngIf?

尝试这样的事情:

// 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;
      }
    });
  }
}