Angular 11 如何检测指定ng-content子元素是否存在以隐藏父div
解决方案
步骤1:修改bs-modal组件的类逻辑(bs-modal.component.ts)
通过@ContentChild装饰器检测是否存在带有[footer]属性的投影内容,代码如下:
import { Component, Input, ContentChild, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-bs-modal', templateUrl: './bs-modal.component.html' }) export class BsModalComponent implements AfterContentInit { @Input() id!: string; // 匹配带有[footer]属性的投影子元素 @ContentChild('[footer]') footerContent?: ElementRef; hasFooter = false; ngAfterContentInit(): void { // 内容投影初始化完成后判断是否存在footer内容 this.hasFooter = !!this.footerContent; } }
步骤2:修改bs-modal组件模板(bs-modal.component.html)
给modal-footer容器添加*ngIf判断,只有存在footer投影内容时才渲染该区域:
<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> <!-- 仅存在footer投影时渲染该区域 --> <div class="modal-footer" *ngIf="hasFooter"> <ng-content select="[footer]"></ng-content> </div> </div> </div> </div>
补充说明
如果需要同时实现header、body区域的可选渲染,按照相同逻辑添加对应的@ContentChild检测和*ngIf判断即可。
内容的提问来源于stack exchange,提问作者Milad Ashrafi
相关产品推荐
相关产品推荐

