Angular2 check/detect ng-content select 存在于父节点 *ngIf 语句

Angular2 check/detect ng-content select exist from parent node *ngIf statement

我的问题是检查父组件中是否提供了与 <ng-content select='some_selector'> 相关的 <some_selector>。也许我举个例子来澄清:

我们有父组件模板(editor.html):

这是我的编辑器

<modal>
    Some contents
    <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>

而在模态组件模板 (modal.html) 中,我们希望使用这样的 *ngIf 语句:

<div class="modal>
    <div class="modal-body">
        <ng-content></ng-content>
    </div>
    <div class="modal-footer" *ngIf='hasNgContent("mfoot")' >
        <ng-content select="mfoot"></ng-content>
    </div>
</div>

如果在 <modal> 标签内的编辑器模板中点头使用 <mfoot> 标签,我们不希望显示 div.modal-页脚。那么如何实现hasNgContent()方法呢?或者可能在 angular2 中有更直接的 *ngIf 语句允许检测 <mfoot> 标签是否用于父组件标签。

您可以使用@ContentChildren 执行此操作并查看集合的长度。类似于:

@ContentChildren(mfootComponent) children: QueryList<mfootComponent>;

这将填充所有 mfootComponents,因此您可以检查是否有任何 mfootComponents。希望对你有帮助。

我找到的解决方案有点脏,使用 jQuery,但我没有在问题框架中看到任何其他方式(因此没有 make 标记 <mfoot> 作为单独的组件):

import { Component, ElementRef, AfterViewInit, ... } from '@angular/core';

declare var $: any;

@Component({
  selector: 'modal',
  templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {

    modalEl = null;

    constructor(private _rootNode: ElementRef) {}

    ngAfterViewInit() {
        this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
    }

    hasNgContent(selector:string) {
        return $(this._rootNode.nativeElement).find(selector).length;
    }
}