2017-01-23 8 views
6

私は、それ自身の中にさまざまなタイプのコンポーネントを動的に作成する角度コンポーネントを持っています。 OnChangesフックを使用して、独自のプロパティを子コンポーネント@Inputのプロパティにバインドします。角2動的コンポーネントのOnPush変化検出

このバインディングは、子コンポーネントの変更検出が[既定]に設定されている場合に正常に機能します。新しい入力が検出され、コンポーネントテンプレートが更新されます。

ただし、変更検出がOnPushの場合は機能しません。変更は検出されません。新しい不変オブジェクト(文字列)がコンポーネント@Inputプロパティに割り当てられているため、変更を検出する必要があります。ここで

は実証するplunkerです: https://plnkr.co/edit/0wHQghtww2HXVbC27bC1

にはどうすればChangeDetectionStrategy.OnPushで動作するように結合、この親ツーダイナミック子プロパティを取得することができますか? OnPushコンポーネントの可能な回避策として

+0

、関連するGitHubの問題は、OnPushの変更検出が動的コンポーネント(つまり、 //github.com/angular/angular/issues/14087 –

答えて

3

cdRef.markForCheck()と共にセッターを使用して次のようになります

興味がある人々のため

変化検出onpush.component.ts

@Component({ 
    selector: 'app-change-detection-onpush', 
    template: ` 
    <div> 
     ChangeDetectionStrategy.OnPush: {{ message || '[blank]' }} 
    </div>`, 
    changeDetection: ChangeDetectionStrategy.OnPush 
}) 
export class ChangeDetectionOnPushComponent implements IMyComponent { 
    private _message: string; 

    constructor(private cdRef: ChangeDetectorRef) {} 

    set message(val: string) { 
    this.cdRef.markForCheck(); 
    this._message = val; 
    } 

    get message() { 
    return this._message; 
    } 
} 

Modified Plunker

+0

偉大な解決策、感謝@yurzui –

関連する問題