如何检查ng-content是否存在

时间:2016-08-01 07:10:47

标签: angular transclusion

假设我有一个简单的Bootstrap面板组件,带有多个转换插槽。模板示例:

<div class="panel panel-default">
  <div class="panel-heading">
    <ng-content select="my-panel-heading"></ng-content>
  </div>
  <div class="panel-body">
    <ng-content select="my-panel-content"></ng-content>
  </div>
</div>

我想让panel-heading可选。如果没有为<div class="panel-heading">

提供内容,如何隐藏<ng-content select="my-panel-heading"></ng-content>元素

3 个答案:

答案 0 :(得分:19)

如果您的父元素<ng-content>包含模板变量(#panelHeading

<div class="panel panel-default">
  <div class="panel-heading" #panelHeading [hidden]="!showHeading">
    <ng-content select="my-panel-heading"></ng-content>
  </div>
  <div class="panel-body">
    <ng-content select="my-panel-content"></ng-content>
  </div>
</div>

然后您可以像

一样查询它
@ViewChild('panelHeading') panelHeading;

并根据是否有孩子设置属性

constructor(private cdRef:ChangeDetectorRef) {}

showHeading:boolean = false;

ngAfterViewInit() {
  this.showHeading = this.panelHeading.nativeElement && this.panelHeading.nativeElement.children.length > 0;
  this.cdRef.detectChanges();
}

如果<my-panel-heading>是Angular2组件,那么您也可以使用

@ContentChild(MyPanelHeading) panelHeading:MyPanelHeading;

constructor(private cdRef:ChangeDetectorRef) {}

showHeading:boolean = false;

ngAfterViewInit() {
  this.showHeading = this.panelHeading != null;
  this.cdRef.detectChanges();
}

答案 1 :(得分:13)

您必须删除所有空间,但如果您真的关心它(ng-content不占用空间),您可以使用CSS执行此操作:

.panel-heading:empty { display: none }

<div class="panel-heading"><ng-content select="my-panel-heading"></ng-content></div>

答案 2 :(得分:2)

做:

<div class="panel panel-default">
  <div class="panel-heading" [hidden]="!panelHeading.hasChildNodes()" #panelHeading>
    <ng-content select="my-panel-heading"></ng-content>
  </div>
  <div class="panel-body">
    <ng-content select="my-panel-content"></ng-content>
  </div>
</div>

请注意,在这种情况下,对于 catch-22 情况,您不能使用 *ngIf