1

私は、コンポーネントのリストをループし、リストからコンポーネントをロードするレイアウトを持っています。 これを実現するには、オブジェクトから定義されたコンポーネントを動的に注入する必要があるため、動的コンポーネントを使用しました。dynamicComponentContainerの使用時に繰り返しの初期化を止める方法

動的に読み込まれたコンポーネントをクリックすると、2,3,4回動的コンポーネントが実行されます。私は子供のコンポーネントであっても、コンポーネントを再初期化する理由を理解できません。これを止める方法があるのか​​、コンポーネントを動的に注入する必要があるのでしょうか。

これは私が動的にコンポーネントを注入し、として子供にお渡しし、作成からデータを取得できません角速度4に現在あるngComponentOutletデータを渡すことができるように発見され、子コンポーネントを注入している唯一の方法です。

Plunker:http://plnkr.co/edit/vslspJ?p=preview

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 

     <buttons (passdata)="getthis($event)" ></buttons> 

     <button (click)="loadDogs()">Load Dogs</button> 
     <hr /> 


     <div *ngFor="let comp of componentlist"> 

     <dynamic-component [componentData]="configureWidget(comp)"></dynamic-component> 
     </div> 
     <hr /> 


    </div> 
    `, 
}) 



export class AppComponent { 


    componentlist:any = [ 
     { name: 'dogs', component: dogsComponent, inputName: 'colordata', inputvalue: 'zzz' }, 
     { name: 'cats', component: catsComponent, inputName: 'showNum', inputvalue: 'zzz' } 
    ] 

    configureWidget(widget){ 
    console.log(widget) 

    if(widget.name == 'dogs'){ 
     return this.componentData = { 
        component: widget.component, 
        inputs: { 
        showNum : 'ddddd', 

        } 
       }; 
    } 
    if(widget.name == 'cats'){ 
     return this.componentData = { 
        component: widget.component, 
        inputs: { 
        colordata : 'ddddd', 

        } 
       }; 
    }  

    } 
+0

あなたのコードがあまりにも混乱しています。 @Input()はcomponentDataを設定します。 componentDataを設定するたびに、新しいコンポーネントを作成し、componentDataを何度か設定するのを見ています。私はsetterメソッドを削除することをお勧めします。コンポーネントデータ(データ:{コンポーネント:任意、入力:任意}) – omeralper

+0

@Omeralper、これについてもっと詳しく説明できますか?あなたは何を意味する代わりにインターフェイスを使用しますか? –

+0

これは単なるコードの可読性のための提案でした。 componentData(data:CustomType) インターフェイスCustomType {コンポーネント:任意、入力:任意}; – omeralper

答えて

1

問題はAppComponentに、あなたが動的コンポーネントにcomponentDataを渡す方法です。 Angularの変更検出は、変更されたかどうかについてはvariableを知っていますが、テンプレートで関数を使用しているかどうかはわかりません。

処理されたデータを渡す関数を使用しないでください。そうしないと、changeDetectionは関数を呼び出し、データを再度処理して渡します。setter関数がdynamic-componentにコールされ、再び初期化されます。

Fixed Plunker

コード:

configuredWidgets = {}; 

    constructor(){ 
    this.componentlist.forEach(comp => { 
     console.log(comp) 

     if(comp.name == 'dogs'){ 
      this.configuredWidgets['dogs'] = { 
         component: comp.component, 
         inputs: { 
         showNum : 'ddddd', 

         } 
        }; 
     } 
     if(comp.name == 'cats'){ 
      this.configuredWidgets['cats'] = { 
         component: comp.component, 
         inputs: { 
         colordata : 'ddddd', 

         } 
        }; 
     }  

    }) 
    } 
関連する問題