2017-08-14 19 views
-1

我想使用通過ng-content傳遞給下列組件的文本。使用@ContentChild查詢ng-Container的文本

@Component({ 
    selector: 'child-component', 
    template: '<ng-content></ng-content>' 
}) 
export class ChildComponent implements AfterContentInit { 
    @ContentChild('value') text: ElementRef; 
    ngAfterContentInit(): void { 
    // This does not work 
    let value = this.text.nativeElement.nextSibling.textContent as string; 
    } 
} 

父組件包括這樣的:

<child-component> 
    <ng-container #value>My Content</ng-container> 
</child-component> 

我怎樣才能從ContentChild字符串 「我的內容」?

+0

它不工作嗎? https://plnkr.co/edit/nkqXNNzBVkZ79PzG8u2u?p=preview – yurzui

回答

0

ng-container轉化爲註釋節點,您將內將呈現爲一個兄弟節點的內容,所以下面:

<ng-container #value>My Content</ng-container> 

轉化爲這樣的事情:

nodes: 
    [<!-- ng contentainer -->] 
    ['My content'] 

因此,您可以使用textContentnodeValue訪問文本nextSibling屬性:

ngAfterContentInit(): void { 
    // This does not work 
    let value = this.vs.nativeElement.nextSibling.nodeValue as string; 
    } 
0

我遇到的問題是,我的內容不是一成不變的:

<child-component *ngFor="let content of array"> 
    <ng-container #value>{{ content }}</ng-container> 
</child-component> 

所以以後我用來代替AfterViewInit生命週期掛鉤AfterContentInit,它工作得很好。 如果內容是靜態的,我的問題中的代碼將是正確的,正如yurzui的評論中注意到的那樣。