HK123
HK123

Reputation: 343

Way to communicate between two sibling components using angular 7 without using a common service for both

Here i want to communicate between two components of a same parent.Basically,i want to pass the data from one component to another.

FirstComponent.ts

constructor(
    private service: service1,
    private serve: service2,
) {}

ngOnInit() {
    this.service.getUser().subscribe((data) => {
        this.serve.setAccount("1", "apple");
        this.serve.setEnvironment("Happy"); 
    })
}

SecondComponent.ts

constructor(private usingService : service2) { }

 ngOnInit() {
 this.Account = this.serve.getAccount();
 this.environmentDetails = this.serve.getEnvironment();

 }

I need to retrieve data from firstComponent to second.here first component is loading after the second component.soo,the data set by first component comes later by in picture.

Tried using subject of rxjs.but,How can we use subject in firstComponent.ts of this example?

How i can communicate between these two components being they are siblings of each other?please help

Upvotes: 6

Views: 9492

Answers (1)

Jason White
Jason White

Reputation: 5833

You could use @Input() @Output() decorators with an EventEmitter. The parent component will set data on the children via a binding. The children will emit new data back to the parent and reset the data that the children receive.

parent.component.ts

@Component({
  selector: 'app-parent',
  template: `
              <app-first-component 
                  [data]="data" (onData)="updateData($event)"></app-first-component>
              <app-second-component 
                  [data]="data" (onData)="updateData($event)"></app-second-component>
            `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  public data: any;

  constructor() {}

  updateData(event) {
    this.data = event;
  }

}

first.component.ts

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements {

  @Input()
  public data: any

  @Output()
  public onData: EventEmitter<any> = new EventEmitter<any>();

  constructor() { }

  updateData(data) {
    //send data back to parent
    //data could be coming from a service/async http request as well.
    this.onData.emit(data)
  }

}

second.component.ts

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements {

  @Input()
  public data: any

  @Output()
  public onData: EventEmitter<any> = new EventEmitter<any>();

  constructor() { }

  updateData(data) {
    //send data back to parent
    //data could be coming from a service/async http request as well.
    this.onData.emit(data)
  }

}

Upvotes: 8

Related Questions