2016-07-09 7 views
1

<some_selector>이 (가) <ng-content select='some_selector'>과 연결되었거나 부모 구성 요소에 연결되어 있는지 확인하는 것이 좋습니다. 분명히 내가이 예를 들어 줄 수 있음 :Angular2 확인/감지 ng-content select 부모 노드에서 존재 * ngIf 문

우리는 상위 구성 요소 템플릿 (editor.html)가 : 여기

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

그리고 모달 구성 요소 템플릿 (modal.html) 우리가 원하는 내 편집기

입니다 <mfoot> 태그가 고개를 끄덕 <modal> 타 내부 편집기 템플릿에 사용 된 경우 우리는 div.modal - 바닥 글을 표시하지 할

<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> 

: 같은 * ngIf 문을 사용하는 지. 그래서 hasNgContent() 메서드를 구현하는 방법은? 또는 angular2에있을 수 있습니다 <mfoot> 태그가 부모 구성 요소 태그에 사용되었는지 여부를 감지 할 수 있도록 허용하는 문이 더 있습니다.

답변

1

@ContentChildren을 사용하여이 작업을 수행하고 컬렉션 길이를 확인할 수 있습니다. 다음과 같이하십시오 :

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

이 모든 mfootComponents로 채워질 것이므로, 있는지 여부를 확인할 수 있습니다. 나는 그것이 도움이되기를 바랍니다. 내가 찾은

+0

mfootComponent 무엇인가? 나는 '모달'과 '편집자'의 두 가지 구성 요소만을 가지고 있습니다. ''태그가 구성 요소가 아닙니다! 그것은 단지 'ng-content select'에만 사용됩니다. –

+0

좋아요, 당신의 아이디어는 무료 태그 likey 을 만들지 않고, 대신 을 componen으로 만듭니다. "out of the box"하지만 받아 들일 것입니다. (그러나 나는 평균 시간 대신 발견 된 대체 솔루션으로 시도하지 않는다.) –

0

이 솔루션은 약간 더럽고 사용 jQuery를,하지만 난 (그래서 별도의 구성 요소로 메이크업 태그 <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; 
    } 
} 
+0

아마도 빼기를주는 대신 구성 요소로 ''을 사용하지 않고 건설적인 솔루션 (hasNgContent 함수 본문)을 제공한다. –