2016-04-24 75 views
2

下面是一個例子:訪問不是組件或html標籤的組件標籤的內部文本?

var ListItem = ng.core.Component({ 
    selector: "item", 
    inputs: ["title"], 
    template: "<li>{{title}} | <ng-content></ng-content></li>", 
}).Class({ 
    constructor: function(){} 
}) 

var ListOne = ng.core.Component({ 
    selector: "listone", 
    queries: { 
     list_items: new ng.core.ContentChildren(ListItem) 
    }, 
    directives: [ListItem], 
    template: "<ul><ng-content select='item'></ng-content></ul>" 
}).Class({ 
    constructor: function(){}, 
    ngAfterContentInit: function(){ 
     console.log(this.list_items); 
    } 
}) 

然後我使用此代碼顯示的組件:

<listone> 
    <item title="first">first</item> 
    <item title="second">second</item> 
</listone> 

哪有ListOne<item>標籤組件訪問的innerHTML的ngAfterContentInit

我想要一個解決方案,而不用另一個標籤包裝內部文本。

回答

2

這需要一點支持ItemComponent的:

export class ItemComponent { 
    title: 'title'; 
    constructor(public elementRef:ElementRef){} 
} 

對於我們設定descendants: true@ContentChildren()

export class ListoneComponent { 
    @ContentChildren(ItemComponent, {descendants: true}) list_items; 

    ngAfterContentInit() { 
    this.list_items.toArray().forEach((item) => { 
     console.log(item.elementRef.nativeElement.innerHTML); 
    }) 
    } 
} 

Plunker example

我希望打字稿代碼仍然是有幫助的,我不知道如何使用Angular和ESx。

+0

在es5中,此示例看起來像這樣https://plnkr.co/edit/EdSONOCq9bfadD42jOj2?p=preview。對不起,但爲什麼我們傳遞具有後代屬性的對象? – yurzui

+0

因爲否則只有直接的孩子返回,但沒有其他後代。因爲這些項目是項目兩層深的孩子只會不工作。感謝ES5 Plunker! –