9

テンプレートを渡すコンポーネントがあります。このコンポーネントの内部では、データを表示できるようにコンテキストを渡したいと思います。Angular2のngOutletContextを使用してテンプレートにコンテキストを渡す

@Component({ 
    selector: 'my-component', 
    providers: [], 
    template: ` 
    <template [ngTemplateOutlet]="templ" [ngOutletContext]="{isVisible: true}"> 
    </template> 
    ` 
}) 
export class MyElementComponent implements OnInit { 
    @ContentChild(TemplateRef) templ; 
    constructor(){} 
} 

他の構成要素の内のコンポーネントを使用して:

<my-component> 
    <template> 
     {{isVisible ? 'yes!' : 'no'}} 
    </template> 
</my-component> 

だからmy-componentに、私は名前templ@ContentChildことによってそれのクラスで処理されたテンプレートを渡しています。

その後、my-componentのテンプレートでは、私はngTemplateOutlettemplを渡していますし、加えて、私はtrueisVisibleセットを持っていngOutletContextを使用してコンテキストを渡しています。

画面にはyes!が表示されますが、コンテキストは決して通過しないようです。

マイ角度バージョン:

"@angular/common": "^2.3.1", 
"@angular/compiler": "^2.3.1", 
"@angular/core": "^2.3.1", 
+0

の変更ログを検索します。あなたは正しい、文脈は決して通過しない。これは、コンテンツとしてに渡すテンプレートが実際にのホストのコンテキストにバインドされているためです。私はこれもやってみたいですが、私はまだ何も見ません。 –

+0

@AlexanderLeonov私の答えを見てください。私はそれを見つけた。 – Tukkan

答えて

23

長い時間の後、私はそれを作りました。単一の値を持つ

例:ループと

@Component({ 
    selector: 'my-component', 
    providers: [], 
    template: ` 
    <template [ngTemplateOutlet]="templ" [ngOutletContext]="{isVisible: true}"> 
    </template> 
    ` 
}) 
export class MyElementComponent implements OnInit { 
    @ContentChild(TemplateRef) templ; 
    constructor(){} 
} 

<my-component> 
    <template let-isVisible="isVisible"> 
     {{isVisible ? 'yes!' : 'no'}} 
    </template> 
</my-component> 

例:

@Component({ 
    selector: 'my-component', 
    providers: [], 
    template: ` 
    <div *ngFor="let element of data"> 
     <template [ngTemplateOutlet]="templ" [ngOutletContext]="{element: element}"> 
     </template> 
    </div> 
    ` 
}) 
export class MyElementComponent implements OnInit { 
    @ContentChild(TemplateRef) templ; 
    constructor(){ 
     this.data = [{name:'John'}, {name:'Jacob'}]; 
    } 
} 

--- 

<my-component> 
    <template let-element="element"> 
     {{element.name}} 
    </template> 
</my-component> 

結果:

<div>John</div> 
<div>Jacob</div> 
+1

ありがとう!これはまさに私が探していたものです。 –

4

ヘッズアップngOutletContextは非推奨とngTemplateOutletContextとして名前が変更されます。

私は同じ問題に直面しています "NgTemplateOutlet#ngTemplateOutletContext"

CHANGELOG

+0

なぜこれが投票されたのですか?ちょうど私がCHANGELOGリンクの書式を短くしなかったからですか?役に立つ情報を投稿してはいけませんか?私はさらに助けになるようにオフになっているので、私を理解するのを助けてください –

+0

私の元のコメントはそれ以来投票されています。もう一度手伝ってください! –

関連する問題