2017-05-01 7 views
2

私はこのContentChildrenクラスセレクタ

@Component({ 
    selector: 'content-com', 
    template: '<ng-content></ng-content>' 
}) 
class ContentComponent { 
    // Select all the elements with .grouped css class 
    @ContentChildren('.grouped') grouped; 
} 

@Component({ 
    selector: 'main-com', 
    template: `<content-com> 
    <div class="grouped"></div> 
    <div class="grouped"></div> 
    </content-com>` 
}) 
class MainComponent { 
} 

のような角度で二つの成分を持っている、それは(私の場合のクラスセレクタで)CSSセレクタを使用して、すべてのコンテンツの子供を選択することは可能ですか?そうでない場合、それを行うための最良のアプローチは何ですか?

答えて

4

ディレクティブを作成することでこれを行うことができます。 Classをセレクタ[class]とし、stringを 'class'にバインドし、入力変数のhostbindingも'class'にバインドします。

はその後@ContentChildren(Class, {descendants: true, read: ElementRef})を行うと、興味のある特定のクラスのためのQueryList

ここでは、スニペットtherevisedされていることをフィルタ:

はまた、あなたが行うことができますPlunker working here

// Remember to declare this in Module 
@Directive({selector: '[class]'}) 
class Class { 
    @HostBinding('class') @Input('class') className: string = '';  
} 

@Component({ 
    selector: 'content-com', 
    template: '<ng-content></ng-content>' 
}) 
class ContentComponent implements AfterContentInit { 
    // Select all the elements with .grouped css class 
    @ContentChildren(Class, {descendants: true, read: ElementRef}) classes: QueryList<ElementRef>; // <--- Note This change 

    get grouped() { 
    if (this.classes && this.classes.length) { 
     return this 
     .classes 
     .map((elRef:ElementRef):Element => elRef.nativeElement) 
     .filter((element: Element) => element.className == "grouped"); 
    } 

    return []; 
    } 

    ngAfterContentInit(){ 

     console.log(this.grouped); // <-- expect (2) [div.grouped, div.grouped]  

    } 
} 
1

を参照してください。それは指示を作成することなく、より簡単です。あなたが知っておくべきことは、ContentChildrenのセレクタが変数名でなければならないということです。だから、:

@Component({ 
 
    selector: 'content-com', 
 
    template: '<ng-content></ng-content>' 
 
}) 
 
class ContentComponent { 
 
    @ContentChildren('grouped') grouped: QueryList<ElementRef>; 
 
} 
 

 
@Component({ 
 
    selector: 'main-com', 
 
    template: `<content-com> 
 
    <div class="grouped" #grouped></div> 
 
    <div class="grouped" #grouped></div> 
 
    </content-com>` 
 
}) 
 
class MainComponent { 
 
}

関連する問題