How to call router outlet child component method from parent comonent

前端 未结 10 1991
甜味超标
甜味超标 2020-12-18 19:42

I am new to angular2


    

I have a button in parent component, if

10条回答
  •  情深已故
    2020-12-18 19:52

    I found two ways to achieve this:

    1. Injecting the main component into children

    You can add an event to your main component, inject the main component to your child components and subscribe to the event. See the plunk that illustrates this. But, now your children have a dependency on your main component. This may be not good.

    main component

    executeAction: EventEmitter = new EventEmitter();
    constructor() { }
    performAction() {
      this.executeAction.emit();
    }
    

    child

    constructor(private appComponent: AppComponent) {
        this.executeAction = this.executeAction.bind(this);
        eventSubscriber(appComponent.executeAction, this.executeAction);
    }
    ngOnDestroy(): void {
        eventSubscriber(this.appComponent.executeAction, this.executeAction, true);
    }
    executeAction() {
        alert('1');
    }
    

    2. Implementing a service

    The best solution here and as described in Parent and children communicate via a service is to create a service that will be an additional layer between the main component and children. In this way, you will be independent from the main component implementation. See the plunk that illustrates this approach.

    service

    subscription = new Subject();
    executeAction() {
        this.subscription.next();
    }
    

    main component

    constructor(private appService: AppService) { }
    performAction() {
      this.appService.executeAction();
    }
    

    child

    constructor(private appService: AppService) {
        this.executeAction = this.executeAction.bind(this);
        eventSubscriber(appService.subscription, this.executeAction);
    }
    ngOnDestroy(): void {
        eventSubscriber(this.appService.subscription, this.executeAction, true);
    }
    executeAction() {
        alert('1');
    }
    

提交回复
热议问题