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

Pass Observable data from Parent Component to a Child Component created with componentFactoryResolver in Angular 2+

我现在有点迷茫,需要帮助。因此,我有一个组件使用 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;

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

如果我的措辞不好或令人困惑,请指出,我会修改问题。

我会使用服务。不是 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);
  }


}

在parent

中的用法
contructor(public yourService:YourService){
}

html 在 parent

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

在child

中的用法
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();
}

}