Ale*_*kov 14 data-binding angular
我正在开发一个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');
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个帮助您理解我的问题的plunker:
对于 angular2 和 Rxjs,“ Observables ”几乎总是答案。
如果我正确理解你的问题,你需要让你的 DynamicComponent 成为“观察者”,让你的容器成为“一个可观察的,甚至更好的一个主题(如果你的容器需要订阅另一个可观察的来接收选择)”。然后,加载动态组件后,将其订阅到您的容器。
每当容器上的选择发生变化时,您都会将新选择推送给订阅者。这样,您可以加载多个动态组件,并且所有组件都会收到您的推送。
容器:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
观察者网:
class DynamicComponent implements Observer{
public currentSelection = {};
next(newSelection){
this.currentSelection = newSelection;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我编辑后的plunker 工作,“假设我将导入更改为最新的 Angular beta.6”
我知道这是一个很老的问题。但希望有人能从这个答案中受益。
| 归档时间: |
|
| 查看次数: |
4968 次 |
| 最近记录: |