将可观察数据从父组件传递到使用Angular 2+中的componentFactoryResolver创建的子组件

时间:2017-09-29 10:49:10

标签: angular angular2-observables

我需要帮助,因为我现在有点迷失了。所以,我有一个使用componentFactoryResolver动态地将子组件绑定到其模板中的组件,这是我的HTML

<div class="dialog">
    <div #container></div>
    <button (click)="move('back')">Back</button>
    <button (click)="move('forwards')">Forwards</button>
</div>

同样在我的组件中我有一个observable,它捕获按钮的点击,就像这样,这是我的(编辑/缩小)代码

// 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;

然而,这只是未定义的,不是我需要的。如何将订阅中的方向数据传递给子组件,或者接收事件/方向字符串需要哪些代码/功能?任何建议都表示赞赏。

如果我的措辞不好或令人困惑,请说出来,我会重写这个问题。

1 个答案:

答案 0 :(得分:3)

我会使用服务。不是ViewChild。通过服务,组件不需要彼此了解

 @Injectable()
  export class YourService {
  move$: Observable<any>;
  private moveSubject: Subject<any> = new Subject();

  constructor() {
    this.move$ = this.moveSubject.asObservable();
  }

  public move(direction) {
     this.moveSubject.next(direction);
  }


}

父母用法

contructor(public yourService:YourService){
}
父母的

html

<button (click)="yourService.move('back')">Back</button>

儿童用法

YourChild implements OnInit, OnDestroy {
    private subscriptions: Subscription = new Subscription();
    constructor(private yourService:YourService) {

    }
    ngOnInit(): void {
        this.subscriptions.add(this.yourService.move$.subscribe(direction => {
            //Do something
        }));        
    }
    ngOnDestroy(): void {
    this.subscriptions.unsubscribe();
}

}