pass data through <router-outlet> using component interaction in angular2

Bahman Rouhani picture Bahman Rouhani · Jul 23, 2017 · Viewed 10.8k times · Source

I'm trying to use this technique intercept input property changes with a setter to pass some data from a parent component to a child component and call a method in child component when the value is changed. my problem is the child component is binded to the parent by <router-link> and when I try to pass the data using:

parent_component.html :

<router-outlet [some_value] = "some_value"></router-outlet>

where some_value is the parameter I am trying to pass from parent to child.

parent_component.ts :

public some_value: string;

and

parent_component.ts :

@Input()
  public set some_vale(number : string){
    this._some_value = number;
  }

however I get the error

Unhandled Promise rejection: Template parse errors: Can't bind to 'some_value' since it isn't a known property of 'router-outlet'.

what am I doing wrong? What is the correct way to pass the data from parent to child component when using a <router-outlet>?

Thanks in advance and any help appreciated.

Answer

egor.xyz picture egor.xyz · Aug 7, 2017

Service:

import {Injectable, EventEmitter} from "@angular/core";    

@Injectable()
export class DataService {
onGetData: EventEmitter = new EventEmitter();

getData() {
  this.http.post(...params).map(res => {
    this.onGetData.emit(res.json());
  })
}

Component:

import {Component} from '@angular/core';    
import {DataService} from "../services/data.service";       
    
@Component()
export class MyComponent {
  constructor(private DataService:DataService) {
    this.DataService.onGetData.subscribe(res => {
      (from service on .emit() )
    })
  }

  //To send data to all subscribers from current component
  sendData() {
    this.DataService.onGetData.emit(--NEW DATA--);
  }
}