2016-03-16 7 views
5

私はこれらの記事とplnkrで説明したように再帰的なコンポーネントを展開しようとしています:Angular2再帰的なコンポーネント

How do I inject a parent component into a child component?

> `http://plnkr.co/edit/l7jsV0k7DbGJGXPFlSPr?p=preview` 

Angular2 Recursive Templates in javascript

しかし、成分のみを扱う提供ソリューションは、オブジェクト自体コンポーネントがインスタンス化するはずのHTMLタグの問題を解決しません。

チャイルドコンポーネントはテンプレート内で<parent> ... </parent> htmlタグをどのように使用できますか?

私は助けを借りて、おそらくplunkr/fiddleに感謝したいと思います。

例外:予期しないディレクティブ値あなたのように、コンポーネントのChildComponent "

の閲覧には「未定義」循環依存の原因があるため

+0

私は自分の携帯電話上でだけだと、あなたのPlunkerを実行することはできませんが、yozrの答えによると、あなたは 'forwardRef'を逃しています。それを使用する方法を示すいくつかの答えがあります。 (downvote was not) –

+0

forwardRefは、Angularが現在のコンポーネントで使用されているディレクティブの依存関係を解決しようとしたときに例外を引き起こす循環依存性であるため、依存関係注入の問題を解決しません。この場合、子コンポーネントの存在のための条件のように使用されるparrentコンポーネントのブール値入力のようなフラグのような条件文も機能しません。問題は、この問題に対する適切な例外が存在しない理由です。 –

+1

Angular1ではなぜこれが可能でしたが、Angular2ではできませんでしたか?これを達成するためにdynamicComponentLoaderをどのように使用しようとしますか? –

答えて

2

望ましい結果は、テンプレートのみを使用することで可能ではありませんthis Plunkerに見ることができます。これは何かが間違っているという兆候です(一般的なDIの問題ではなく、角度の問題)。

子に依存parentComponentに:循環依存関係が発生し、親に依存

import {Component} from 'angular2/core'; 
import {AppComponent} from './app.component'; 
import {ChildComponent} from './child.component' 

@Component({ 
    selector: 'parent', 
    template: `<p>parent</p> 
    <child></child>`, 
    directives: [ChildComponent] 
}) 
export class ParentComponent { 
    constructor() {} 
} 

ChildComponent:

import {Component} from 'angular2/core'; 
import {AppComponent} from './app.component'; 
import {ParentComponent} from './parent.component'; 

@Component({ 
    selector: 'child', 
    template: `<p>child</p> 
    <parent></parent>`, 
    directives: [ParentComponent] 
}) 
export class ChildComponent { 
    constructor() {} 
} 

あなたはこのexampleに見るが、覚えることができるよう、あなたがDynamicComponentLoaderを使用することによって、これを達成することができますしかし、無限のコンポーネントレンダリングを停止するための何らかの種類の条件を提供します。私の例では条件は親コンポーネントで入力パラメータです:

import {Component, Input} from 'angular2/core'; 
import {AppComponent} from './app.component'; 
import {ChildComponent} from './child.component' 

@Component({ 
    selector: 'parent', 
    template: `<p>parent</p> 
    <child *ngIf="condition"></child>`, 
    directives: [ChildComponent] 
}) 
export class ParentComponent { 
    constructor() { 
    } 

    @Input() condition: bool; 
} 
+1

note DynamicComponentLoaderは、現在、ComponentResolverおよび/またはComponentFactoryResolverに置き換えられています。 –