For this kind of situation i recommend share variable state inside the whole application using such library like rxjs :
Going step by step .. first create new service SharedService contain two variables :
(i recommend to take a look on this link to learn more about behaviorSubject and Observable if you don't have idea about the it BehaviorSubject vs Observable?)
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
user = new BehaviorSubject({name: 'default name'}) ;
userObservable = this.user.asObservable() ;
constructor() { }
changeUser(newObject){
this.user.next(newObject) ;
}
}
moving to the component1 . First we have to subscribe to the SharedService userObservable variable . and have the ability to change the service variable value or moving to component 2 :
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { SharedService } from '../services/shared.service'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class Component1 implements OnInit {
user ;
constructor(private sharedSerivce : SharedService,
private router : Router
) { }
ngOnInit(): void {
this.sharedSerivce.user.subscribe(currentUser=>{
this.user= currentUser ;
})
}
saveUser() {
this.sharedSerivce.changeUser({name : 'new user '}) ;
}
goToComponent2(){
this.router.navigate(['/component2'])
}
}
and the component1 html file will be as follow :
<h1>Component 1</h1>
<p>current user name is {{user.name}}</p>
<button (click)="saveUser()">
change user name to 'new user'
</button>
<br>
<button (click)="goToComponent2()">
goToComponent2
</button>
in the component 2 also we have to subscribe to the service userObservable variable and even changing this value or returning to component1
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { SharedService } from '../services/shared.service';
@Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.scss']
})
export class Component2 implements OnInit {
user ;
constructor(private sharedSerivce : SharedService,
private router : Router
) { }
ngOnInit(): void {
//each time the component 1 loaded will synchronise the value of its user proprty with the value saved in the serivce
this.sharedSerivce.user.subscribe(currentUser=>{
this.user= currentUser ;
})
}
saveUser() {
this.sharedSerivce.changeUser({name: 'default user'}) ;
}
goToComponent1(){
this.router.navigate(['/component1'])
}
}
also the component2 html content will not be far away than component 1
<h1>Component 2</h1>
<p>current user name is {{user.name}}</p>
<button (click)="saveUser()">
change user name to 'default user'
</button>
<br>
<button (click)="goToComponent1()">
Back To Component1
</button>