11

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.

AT82
  • 71,416
  • 24
  • 140
  • 167
Bahman Rouhani
  • 1,139
  • 2
  • 14
  • 33
  • until now, there is no property binding in , you can use services in order to communicate between components. – Raed Khalaf Jul 23 '17 at 08:42
  • so there is simply no way to do this? – Bahman Rouhani Jul 23 '17 at 08:44
  • 1
    I think you can't do that this way. If you want to send data from the router to the child, declare a Service and use a Observable to send your object. You'll do a .next(your-object) on the component where the router is declared, and a .subscribe(object => {...}); on the child component – Mattew Eon Jul 23 '17 at 08:44
  • Possible duplicate of [Passing data into "router-outlet" child components (angular 2)](https://stackoverflow.com/questions/41451375/passing-data-into-router-outlet-child-components-angular-2) – AT82 Jul 23 '17 at 08:46
  • no, bcs when using property binding, you bind a property which surly must be exist, but you cant make sure that it will be exist in . – Raed Khalaf Jul 23 '17 at 08:46
  • I will use services then. thanks for your help. – Bahman Rouhani Jul 23 '17 at 08:47

1 Answers1

10

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--);
  }
}
Community
  • 1
  • 1
egor.xyz
  • 2,847
  • 1
  • 21
  • 18