Angular2: Two-way data binding on component dynamically inserted using DynamicComponentLoader

前端 未结 2 1915
暖寄归人
暖寄归人 2021-02-19 10:17

I am developing an Angular2 app, and I faced a problem:

I have a set of different objects that can be selected using UI. Each of this objects has a set of options (diffe

相关标签:
2条回答
  • Here is what you can do, move your code from constructor to ngOnInit and use promises for assigning dynamic value.

    ngOnInit(){
        this.dynamicComponentLoader.loadIntoLocation(DynamicComponent, this.elementRef,'container').then((component)=>{
            component.instance.currentSelection = currentSelection;
        });
    }
    
    0 讨论(0)
  • 2021-02-19 10:43

    With angular2 and Rxjs, "Observables" are almost always the answer.

    If i understood your problem correctly, you need to make your DynamicComponent an "Observer" and your container "an Observable or even better a Subject (In case your container needs to subscribe to another observable to receive selections from)". Then, after loading your dynamic component, subscribe it to your container.

    Whenever the selection changes on your container, you push the new selection to your subscribers. This way, you can load multiple dynamic components and all will receive your pushes.

    The Container:

    class App {
      currentSelection = {};
      selections = [
        {name: 'Selection1', property1: 10, property2: 'test'},
        {name: 'Selection2', property1: 20, property2: 'test2'}
      ];
      subject:Subject<any> = new Subject();
    
      constructor(private loader: DynamicComponentLoader, private elementRef: ElementRef) {
      }
    
      ngOnInit(){
        this.loader.loadIntoLocation(DynamicComponent, this.elementRef, 'container', this.injector)
        .then(compRef =>this.subject.subscribe(compRef.instance));
        // subscribe after loading the dynamicComponent
      }
    
      // set the new selection and push it to subscribers
      changeSelection(newSelection){
        this.currentSelection = newSelection;
        this.subject.next(this.currentSelection);
      }
    }
    

    The Observer:

    class DynamicComponent implements Observer{
      public currentSelection = {};
    
      next(newSelection){
        this.currentSelection = newSelection;
      }
    }
    

    Here is your plunker working after my edits, "provided I changed the imports to the newest angular beta.6"

    I know this is a quite old question. But hopefully someone will benefit from this answer.

    0 讨论(0)
提交回复
热议问题