2016-10-10 1 views
3

다른 구성 요소를 동적으로 추가하는 구성 요소를 작성하려고합니다. 예를 들어 여기 내 부모 클래스이므로 :각도 2 동적 양방향 바인딩

import { Component, ComponentRef, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'; 

@Component({ 
    templateUrl: './app/sample-component.component.html', 
    selector: 'sample-component' 
}) 
export class SampleComponent { 

    @ViewChild('dynamicContent', { read: ViewContainerRef }) 
    protected dynamicComponentTarget: ViewContainerRef; 
    private currentComponent: ComponentRef<any>; 
    private selectedValue: any; 

    constructor(private componentResolver: ComponentFactoryResolver) { 

    } 

    private appendComponent(componentType: any) { 
     var factory = this.componentResolver.resolveComponentFactory(componentType); 
     this.currentComponent = this.dynamicComponentTarget.createComponent(factory); 
    } 
} 

sample-component.component.html:

<div #dynamicContent></div> 

그것은 요소를 추가로 잘 작동하지만 난에서처럼, 동적으로 두 방법을 결합하는 방법에 대한 아무 생각이 없다 정적 구성 요소 : [(ngModel)]="selectedValue"

답변

4

동적으로 추가 된 구성 요소를 사용한 바인딩은 지원되지 않습니다.

당신은 동적으로 추가 구성 요소 (https://angular.io/docs/ts/latest/cookbook/component-communication.html)
또는 당신이 읽을 수와 통신 할 수있는 공유 서비스를 사용할 수 있습니다/명령 적 this.currentComponent 참조를 사용하여 설정 :

private appendComponent(componentType: any) { 
    var factory = this.componentResolver.resolveComponentFactory(componentType); 
    this.currentComponent = this.dynamicComponentTarget.createComponent(factory); 
    this.currentComponent.instance.value = this.selectedValue; 
    this.currentComponent.instance.valueChange.subscribe(val => this.selectedValue = val); 
} 
+0

좋아, 나는 그것을'ControlValueAccessor을 사용하는 것이 더 좋다고 생각한다 '인터페이스,하지만'[(ngModel)] = "selectedValue"'와 같은 구성을 제공하는 컴포넌트가이 인터페이스를 inmplements하는지 확실하지 않습니다. 이렇게하면이 방법으로 사용할 수 있습니다. this.currentComponent.instance.registerOnChange (this.valueChangeHandler); ' – SergeyK

+0

무슨 뜻인지 확실치 않습니다. '[(ngModel)] = "..."'이 작동하려면'ControlValueAccessor' 구현이 필요하지만 Angular2 바인딩이기 때문에 동적으로 추가되는 구성 요소에서는 지원되지 않습니다. –

+0

이 @ GünterZöchbauer를 확장 해 주시겠습니까? this.currentComponent.instance.value는 를 대체하기 위해 componentTypes template : '...'내부의 DOM 입력 요소와 어떻게 연관됩니까? 당신이 멍청이를 공유 할 수 있다면 가장 감사 할 것입니다. –