1
votes

I tried and able to send data from a parent component to child component using @input()

Now I'm trying to send the data from parent to child component upon an event. Ie.. Whenever the user enters some data in the parent component text box and hit "send to the button", it should display the value in the child component.

enter image description here

So, can someone please help me with this. Thanks!

1
Can you show your code here so we can find the problem?Gourav Garg
there is A TON of similar questions already, please search or check documentation angular.io/guide/… . Your options are intercepting input value change, emitting custom event or even using separate service for communication though this option is usually the best for sibling component interactionsihorbond
Does this answer your question? Child listens for parent event in Angular 2ihorbond
you forgot to explain the problem here@Prashant Pimpale

1 Answers

1
votes

This a way I know. Please search for more... First, you have to create a service like this and create new BehaviorSubject,

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class InitialService {

  value = new BehaviorSubject<string>(null);

  constructor() { }

  setValue(inputValue) {
    this.value.next(inputValue);
  }

  getValue(): Observable<string> {
    return this.value.asObservable();
  }
}

next, you can create parent component.ts like this (consider that I used app component),

import { Component } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { InitialService } from './services/initial.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  value = new BehaviorSubject<string>(null);

  constructor(private initialService: InitialService) { }

  onClickMe(inputValue) {
    this.initialService.setValue(inputValue);
  }

  getValue(): Observable<string> {
    return this.value.asObservable();
  }
}

Your parent component.html,

<h1>Parent Component</h1>
<input #inputValue type="text">
<button (click)="onClickMe(inputValue.value)">Send to Child</button>
<app-child></app-child>

Your child component.ts,

import { Component, OnInit } from '@angular/core';
import { InitialService} from '../../services/initial.service'
import { Observable } from 'rxjs';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  value: Observable<string>;

  constructor(private initialservice: InitialService) {
    this.value = initialservice.getValue();
  }

  ngOnInit() {
  }

}

Your child component html,

<h1>Child Component</h1>
<p>value: {{value | async}}</p>

if there are unclear things, let me know. Thank you.