Manish Salunke
Manish Salunke

Reputation: 63

how to communicate beetween 2 sibling component in angular 4?

i want to checkbox tick in one component and show data in different component when checkbox checked.

component 1

<div class="col-md-6" *ngFor="let mapLegend of mapLegends">
            <label class="checkbox">
            <input type="checkbox"
            name="mapLegend"
            value="{{mapLegend.name}}"                            
            [(ngModel)]="mapLegend.checked"/>
            <span class="checkbox__input"></span>
            <span class="checkbox__label"> {{mapLegend.name}}</span>
            </label>
 </div>

component 2 want data if mapLegend.checked

Upvotes: 1

Views: 203

Answers (3)

Shashank Vivek
Shashank Vivek

Reputation: 17504

There are several ways to do it. From your requirement, I consider that you want to observe the changes made in either of the components. So I'll suggest you to go for subject.

Create a subject in a service. Now, subscribe to the variable in the components where you want to listen to any changes that has been.

export class SomeService{
    public mySubject = new Subject();
    choice: []<any>;

    insertCheckBoxValue(val){
        this.choice.push(val);
        this.mySubject.next('the value you want to transmit to all Subscribers'); // Let's say: Yoda
    }
}


export class Component1{
    constructor(private svc: SomeService){}

    this.svc.mySubject().subscribe( val => console.log(val)) // this will listen to the changes of Comp2 : Yoda

    checkBoxClicked(someVal){
        this.svc.insertCheckBoxValue(someVal);
    }

}

export class Component2{
    constructor(private svc: SomeService){}

    this.svc.mySubject().subscribe( val => console.log(val)) // this will listen to the changes of Comp1 : Yoda

    checkBoxClicked(someVal){
        this.svc.insertCheckBoxValue(someVal);
    }

}

If you want to share the data, then create a variable in SomeService file and get its value whenever .next() is fired. You can actually share a common value from .next(your_value) and then subscribing it in another component.

Here is the demo as you asked & Here is the code

Tweak the above code to suit your requirement and increase efficiency. It has to be improved to match your specific needs

Upvotes: 2

Yanis-git
Yanis-git

Reputation: 7875

Still @Shashank Vivek is most generic way to do cross component communication. If what you need is simply what you have discribe : if my checkbox is true, then initialize childComponent with my model as parameter, then you can do something like this :

Component :

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  mapLegends: Array<{
    checked: boolean,
    name: string
  }>;

  constructor() {
    this.mapLegends = [
        {
          checked: false,
          name: 'Check 1'
        },
        {
          checked: false,
          name: 'Check 2'
        }
    ];
  }

  onCheckboxChange(index: number) {
    console.log(index);
    console.log(this.mapLegends[index]);
  }
}

html :

<div class="col-md-6" *ngFor="let mapLegend of mapLegends; let i = index">
    <label class="checkbox">
      <input type="checkbox"
      name="mapLegend"
      value="{{mapLegend.name}}"                            
      [(ngModel)]="mapLegend.checked" 
      (change)="onCheckboxChange(i)" />
      <span class="checkbox__input"></span>
      <span class="checkbox__label"> {{mapLegend.name}}</span>
    </label>
 </div>


 <div class="col-md-6" *ngFor="let mapLegend of mapLegends; let i = index">
   <hello *ngIf="mapLegend.checked" [name]="mapLegend.name"></hello>
 </div>

Online version

UPDATE 1

On Component.ts in following code you can do any traitment you want :

//This callback will be call on any change from checkbox. Up to you to do what ever you want.
  onCheckboxChange(index: number) {
    if(this.mapLegends[index]) {
      // Do what ever you want
      console.log(this.mapLegends[index]);
    }
  }

or in component.html :

 <div class="col-md-6" *ngFor="let mapLegend of mapLegends; let i = index">
<!-- this section will be display only if checkbox is checked. -->
   <div *ngIf="mapLegend.checked">
      hello {{ mapLegend.name }} i am happy to see you.
   </div>
 </div>

Upvotes: 1

Hamed Baatour
Hamed Baatour

Reputation: 6932

You could use a shared service and send a notification from any component injecting the service.

Consider the following :

checkbox.service.ts

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


@Injectable()
export class CheckboxService {
  // initial value false (not checked)
  public checkbox = new BehaviorSubject<boolean>(false);
  checkboxObservable = this.checkbox.asObservable();

  changeCheckboxState (value: boolean): void {
    this.checkbox.next(value);
  }
}

And then in your components:

reciver.component.ts

To get the checkbox state you do:

constructor(private cs: CheckboxService) {
    this.cs.checkboxObservable
       .subscribe((checkboxState) => {
              // getting the value
              console.log(checkboxState);
          });
    }

sender.component.ts

To set a new state for the checkbox you simply use:

changeCheckboxState(){
this.cs.changeCheckboxState(this.mapLegendCheckbox);
}

Note don't forget to add the service in the provides arrays and the component in the declarations array of the same module so you don't get any errors.

Upvotes: 1

Related Questions