Angular2:使用 DynamicComponentLoader 动态插入组件上的双向数据绑定

2024-03-18

我正在开发 Angular2 应用程序,遇到一个问题:

我有一组可以使用 UI 选择的不同对象。每个对象都有一组可以使用 UI 进行编辑的选项(不同对象不同)。现在,我使用 DynamicComponentLoader 为当前选定的对象插入特定组件,以便它可以正确处理其选项。 问题是我不知道如何将当前选定对象的数据绑定到动态插入的选项组件。

@Component({
  selector: 'dynamic',
  template: `<div>Options:</div>
             <div>Property1: <input type="number" /></div>
             <div>Property2: <input type="text" /></div>`
  // template: `<div>Options:</div>
  //           <div>Property1: <input type="number" [(ng-model)]="currentSelection.property1" /></div>
  //           <div>Property2: <input type="text" [(ng-model)]="currentSelection.property1" /></div>`
})
class DynamicComponent {

}


@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Selected: {{currentSelection.name}}!</h2>
      <div  #container></div>
    </div>
  `
})
class App {
  currentSelection = {name: 'Selection1', property1: 10, property2: 'test'};

  constructor(private loader: DynamicComponentLoader, private elementRef: ElementRef) {
    loader.loadIntoLocation(DynamicComponent, elementRef, 'container');
  }
}

Here http://plnkr.co/edit/o3pHjJNwuw4nzGeyqiju?p=preview是一个帮助你理解我的问题的笨蛋:


使用 angular2 和 Rxjs,“观测值 https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md“几乎总是答案。

如果我正确理解你的问题,你需要使你的 DynamicComponent 成为“Observer https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observer.md“和你的容器”an可观察的 https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md甚至更好Subject https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md(如果您的容器需要订阅另一个可观察对象来接收选择)”。然后,在加载动态组件后,将其订阅到您的容器。

每当容器上的选择发生更改时,您都会将新选择推送给订阅者。这样,您可以加载多个动态组件,并且所有组件都会收到您的推送。

容器:

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);
  }
}

观察者网:

class DynamicComponent implements Observer{
  public currentSelection = {};

  next(newSelection){
    this.currentSelection = newSelection;
  }
}

这是你的plunker http://plnkr.co/edit/08VFZIz74GWrZht9FXl2?p=preview编辑后工作,“前提是我将导入更改为最新的 Angular beta.6”

我知道这是一个很老的问题。但希望有人能从这个答案中受益。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2:使用 DynamicComponentLoader 动态插入组件上的双向数据绑定 的相关文章

随机推荐