2016-10-10 7 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", вводит этот интерфейс. Таким образом, он может использоваться таким образом 'this.currentComponent.instance.registerOnChange (this.valueChangeHandler);' – SergeyK

+0

Не уверен, что вы имеете в виду. Реализация 'ControlValueAccessor' требуется для' [(ngModel)] = "..." 'для работы, но это также привязка Angular2 и, следовательно, не поддерживается динамически добавленными компонентами. –

+0

не могли бы вы рассказать об этом @ GünterZöchbauer? Как this.currentComponent.instance.value ассоциируется с элементом ввода DOM внутри шаблона componentTypes: '...' для замены ? Я был бы очень признателен, если бы вы могли поделиться плунжером. –

Смежные вопросы