2
votes

I want to pass data between two independent components.

For example:

  1. I have first component with input text and submit button. Second component with input box
  2. When user enters data in text box of first component and clicks submit he will be routed to second component where data entered in input textbox of first component should come inside textbox of second component.
  3. I tried using @Input and @Output but this is for parent child hierarchy.
  4. In my case I have 2 separated components where user routes from one page to another were whole view changes
  5. I heard to make use of service but was not able to find proper example or documentation online.
1
You can use subject in the child component and then subscribe to it in the parent component. LinkTunisiano32
@Tunisiano32 answer works if you do it in a shared service.Yeysides

1 Answers

0
votes

You can make a common service, I name it as store. For example, you can make a forms store forms.store.ts. This store will be a service

@Injectable()
export class FormsStore {
  inputText : string = '';
  constructor(){
       //Code here
  }
  //Other Functions 
}

In form.component.ts :

 @Component({
    selector: 'form',
    encapsulation: ViewEncapsulation.None,
    template: require('./form.component.html')
})

export class FormComponent{

  constructor(private store: FormsStore) {
  }

  onFormSubmit(value){
   this.store.inputText = value;
  }

}

In form.component.html :

<input (keydown.enter)="onFormSubmit(input.value)" #input>

Now in other components, you can again create an instance of the store and refer to 'inputText' value as store.inputText and use it.