Home > OS >  Two Way Binding between Sibling Components
Two Way Binding between Sibling Components

Time:07-10

I am having an issue where i can't pass data from one component to the next using 2-way binding.

The structure is this

<div >
<component-one> "Containers Input Tag" and ngModel </component-one>
<router-outlet>
<component-two></component-two>
<component-three></component-three>
</router-outlet>
</div>

Component-One has this Template

<input  [(ngModel)]="model_data">

How do i get model-data into all other components i need them to be?

This is a .ts file with what i am trying to implement

I would like to use the string generated from the

component-one

export class ComponentOne implements OnInit {

model_data = 'model_string';
items: Observable<any[]>;
constructor(private dataService: DataService) {


}

ngOnInit(): void {
}

update() {
this.dataService.updateData(this.model_data);
}
}

The other Components are as follows

export class ComponentTwo implements OnInit {


model_data = model_string;
title = 'First';
items: Observable<any[]>;
constructor(db: AngularFireDatabase, private titleService: Title, private meta: Meta, private dataService: DataService) {
this.items = db.list(this.model_data, ref => ref.limitToLast(100)).valueChanges().pipe(map(values =>     values.reverse()));

}

ngOnInit(){
this.titleService.setTitle(this.title);
this.meta.addTag({name: 'Negligible', content: 'Negligible'});
}

subscribeToData() {
this.dataService.dataObservable$.subscribe((data) => (this.model_data = data));
}

The Service file

export class DataService {

model_data= model_string;
constructor() {

}

public subject = new Subject<any>();
dataObservable$ = this.subject.asObservable();

updateData(data: any) {
this.subject.next(data);
}

}

CodePudding user response:

For inter child data communication, it's better to use subject or behavior, that allows the publish/subscribe mechanism.

In a service file, define a subject:

SomeServie {
  private dataSource = new Subject<any>();
  dataObservable$ = this.dataSource.asObservable();

  updateData(data: any) {
    this.dataSource.next(data);
  }

}

From your component-one.ts, publish the event to dataSource:

<input  [(ngModel)]="model_data" (blur)="update()">

update() {
  this.someService.updateData(this.model_data);
}

In component-two and component-three, subscribe to dataObservable:

subscribeToData() {
   this.someService.dataObservable$.subscribe((data) => {
     // data is the model_data passed from component-one   
   });
}

Whenever, component-one publishes data, this observable will capture the emitted value every time.

Don't forget to declare the service in each component's constructor.

constructor(..., private someService: SomeService) {}

Stackblitz Demo

  • Related