2016-09-26 10 views
0

ギュンターの答えのおかげで更新し、今、私はより良い私が求めているものを理解していること:angular2ディレクティブは、適用されているコンポーネントのテンプレートにアクセスできますか?

を私はカスタムディレクティブを書いていると私はコンポーネントに適用することを計画している場合、私を持っているための最良の方法は何でしょうそのコンポーネントのテンプレートを指示しますか?

私はホストで見つかった最初のカスタムボタンコンポーネントのスタイリングを変更するだけの目的を持った属性ディレクティブを作成しています。ホスト自体が私のカスタムボタンコンポーネントである場合、それは何らかの理由で私のディレクティブのContentChildrenクエリに表示されます。そして、ホストがその代わりに私のカスタムボタンコンポーネントをそのテンプレートに含んでいれば、私のディレクティブはそれを見つけることができません。

ここに私のディレクティブです:

import { Directive, AfterViewInit, AfterContentInit, ContentChildren, QueryList, ViewChild, ElementRef } from '@angular/core'; 
import { MyCustomButtonComponent } from './my-custom-button.component'; 

@Directive({ 
    selector: '[specialButton]' 
}) 
export class SpecialButtonDirective implements AfterViewInit, AfterContentInit { 

    hostElement: ElementRef; 
    @ViewChild(MyCustomButtonComponent) myCustomButtonViewChild; 
    @ContentChildren(MyCustomButtonComponent, {descendants: true}) myCustomButtonQueryList: QueryList<MyCustomButtonComponent>; 

    constructor(el: ElementRef) { 
     this.hostElement = el; 
    } 

    ngOnInit() { 
     //Should I query here? Via this.hostElement.nativeElement.querySelector(...) perhaps? 
    } 

    ngAfterContentInit(): void { 
     console.log('Value of myCustomButtonQueryList.first [' + this.myCustomButtonQueryList.first + ']'); 
    } 
    ngAfterViewInit(): void { 
     console.log('Value of myCustomButtonViewChild [' + this.myCustomButtonViewChild + ']'); 
    } 
} 

そしてそのディレクティブでMyCustomButtonComponentとSpecialButtonDirectiveを含み、私の主成分で:最初の例は私のカスタムを見つけ、なぜ

<my-custom-button specialButton>Host is Button</my-custom-button> 
<!-- Value of myCustomButtonQueryList.first [[object Object]] --> 
<!-- Value of myCustomButtonViewChild [undefined] --> 

<!--The dropdown toggle button is a my-custom-button in my-custom-dropdown's template --> 
<my-custom-dropdown specialButton> 
    <ul> 
     <li><div>Item 1</div></li> 
     <li><div>Item 2</div></li> 
    </ul> 
</my-custom-dropdown> 
<!-- Value of myCustomButtonQueryList.first [undefined] --> 
<!-- Value of myCustomButtonViewChild [undefined] --> 

私は理解していませんContentChildrenはng-contentタグ内でのみ検索されると思っていたが、ホストMyCustomButtonComponentを取得していると思っていたからだ。

私はViewChildが私のカスタムドロップダウンのテンプレートを検索すると考えていたので、2番目の例がうまくいかない理由は分かりません。それでもMyCustomButtonComponentのインスタンスが見つかりません。

答えて

4

ディレクティブにはビューがないため、@ViewChild()は機能しません。しかし@ContentChildren()はサポートされています。

+0

ありがとうございます!ディレクティブが適用されているコンポーネントのテンプレートで定義されたコンテンツを取得する方法はありますか?例えば。私のディレクティブを自分のコンポーネント(私のカスタムドロップダウン)に適用すると、私のディレクティブがmy-custom-dropdownのテンプレートで定義された別のコンポーネントにアクセスする方法がありますか? – SnoopDougg

+0

私は本当に頼んでいることをよく理解するようになったので、私の質問を更新しました。 – SnoopDougg

関連する問題