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

流过昼夜 提交于 2019-12-04 09:44:18

I would use a service. Not ViewChild. With a service the components would not need to know of each other

 @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);
  }


}

Usage in parent

contructor(public yourService:YourService){
}

html in parent

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

Usage in 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();
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!