【发布时间】:2017-09-29 10:49:09
【问题描述】:
我需要帮助,因为我现在有点迷路。所以,我有一个组件,它使用 componentFactoryResolver 将子组件动态注入其模板,这是我的 HTML
<div class="dialog">
<div #container></div>
<button (click)="move('back')">Back</button>
<button (click)="move('forwards')">Forwards</button>
</div>
在我的组件中,我也有一个可观察的对象,可以像这样捕获按钮的点击,这是我的(编辑/简化)代码
// parent-component.ts
@ViewChild('container', {read: ViewContainerRef})
public dialogContainer: ViewContainerRef;
public navigationClick$: Observable<string> = new Subject<string>();
// click event on buttons
public move(direction): void {
this.navigationClick$.next(direction);
}
// code to inject child dynamic component, please ignore the args / variables
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.data.component);
this.componentRef = this.dialogContainer.createComponent(componentFactory);
this.embeddedcomponent = this.componentRef.instance as IWizardDialog;
this.embeddedcomponent.data = this.data.data;
现在我想将来自 navigationClick$ 的最新可观察值传递给子组件,因此我修改了父组件中的代码...
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.data.component);
this.componentRef = this.dialogContainer.createComponent(componentFactory);
// NEW CODE
// here I subscribe to the observable and try to pass the value to the child component
this.navigationClick$.subscribe((data: string) => {
this.componentRef.instance.direction = data;
});
this.embeddedcomponent = this.componentRef.instance as IWizardDialog;
this.embeddedcomponent.data = this.data.data;
正如我所料,订阅在父组件中工作,但是我不确定如何捕获/传递订阅数据到子组件,例如我可以将其声明为Input()
// child-component.ts
@Input() public direction: string;
但是,这只是未定义的,不是我需要的。如何将订阅中的方向数据传递给子组件,或者我需要什么代码/功能来接收事件/方向字符串?任何建议表示赞赏。
如果我的措辞不好或令人困惑,请说出来,我会修改问题。
【问题讨论】:
-
如果用户点击浏览器后退按钮,您希望应用程序如何运行?您是否希望它与 一样。或者您是否希望它转到用户访问的最后一页。如果你想让它退一步“对话”,你应该使用角度路由。前后移动可以是 [routerLink] 到具有不同 url 参数的同一页面。
-
行为无所谓,我导航的是数据而不是窗口,我只是想把字符串传给孩子,一切都搞定了。
-
好的答案即将发布
标签: angular angular2-observables