I am experimenting with Angular 8. I have two forms in two different components that share some input values and they update every time the user leaves the input field.
Component 1 has these input fields
<input matInput [(ngModel)]="first" (blur)="newMessage()">
<input matInput [(ngModel)]="last" (blur)="newMessage()" >
and component 2 has these input fields
<input matInput [(ngModel)]="first2" >
<input matInput [(ngModel)]="last2" >
To share the values, I created a service that looks like this
export class DataService
{
private MessageSource = new BehaviorSubject<UserData[]>([]);
currentMessage = this.MessageSource.asObservable();
constructor( ) { }
changeMessage(message : UserData[]){
this.MessageSource.next(message)
}
}
and the UserData class used
class UserData{
firstname : string
lastname : string
}
First component has this code associated with it
export class Comp1Component implements OnInit {
message : UserData[]
first : string
last : string
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.first = message)
}
name
newMessage(){
this.data.changeMessage(this.first)
}
}
and the second looks like this
export class Comp2Component implements OnInit {
message : UserData[]
first2 : string
last2: string
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.first2 = message)
}
}
Right now this code updates the first input field on the second component. I would like to pass the second input value also, but I don't know what I have to do... Any ideas?
Here is the example https://stackblitz.com/edit/angular-e5k2vm
If anyone could help, I would apprecciate it...
Try like this:
Working Demo
data.service
private MessageSource = new BehaviorSubject<UserData>({});
currentMessage = this.MessageSource.asObservable();
constructor( ) { }
changeMessage(message : UserData){
this.MessageSource.next(message)
}
.comp1
ngOnInit() {
this.data.currentMessage.subscribe(message => {
this.first = message.first;
this.last = message.last;
});
}
name;
newMessage() {
this.data.changeMessage({ first: this.first, last: this.last });
}
.comp2
ngOnInit() {
this.data.currentMessage.subscribe(message => {
this.first2 = message.first;
this.last2 = message.last;
});
}
newMessage() {
this.data.changeMessage({first:this.first2,last:this.last2});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With