簡體   English   中英

Angular2 檢查/檢測 ng-content 從父節點中選擇存在 *ngIf 語句

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

我的問題是關於檢查<some_selector>具有連接<ng-content select='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-footer。 那么如何實現hasNgContent()方法呢? 或者可能在 angular2 中有更直接的*ngIf語句,允許檢測<mfoot>標簽是否在父組件標簽中使用。

您可以使用@ContentChildren 執行此操作並查看集合的長度。 就像是:

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

這將填充所有 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM