使用 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”
我知道这是一个很老的问题。但希望有人能从这个答案中受益。