Skip to content Skip to sidebar Skip to footer

Changing Value In One Component Affects Another

I have an angular 6 application, which has a top bar and a content area below this. These are different component and I am currently developing the user profile page. Name of the u

Solution 1:

Next time post a bit of code. Since there isn't, I'll show you how to do it with an example.

Let's assume we have two component, A and B. And the changes will be reflected on both of two components.

Service :

export classYourService{
  privatedata$ = new BehaviorSubject<string>(null);
  data = this.data$.asObservable();

  public setData(data: string){
    this.data$.next(data);
  }
}

Component A/B.html :

<div>{{something}}</div>

Component A/B.ts :

isAlive = true;
something: string;

constructor(private service: YourService
) { }

ngOnInit(){
  this.service.data
  .takeWhile(() =>this.isAlive)
  .subscribe( res => {
    if(!!res){
      this.something = res;
    }
  });
}

    ngOnDestroy(){
      this.isAlive = false;
    }

Component that change the status:

exportclassAnotherComponent{
  constructor(private service: YourService
  ) { }

  privatechangeData(data: string){
    this.service.setData(data);
  }
}

Now everything is working fine. BehaviorSubject allow the communication between components. whenever the function changeData is fired, you will see the changes on both of your components.

takeWhile is for unsubscribing when the component die.

If you have more question, feel free to ask them to me and I will edit this answer.

Solution 2:

You can create service to exchange data between components. It could be UserService that provide access to current user information.

@Injectable()
export classUserService {
    user: UserInfo;
    // define user here (load from backend or somehow else)
}

In user-profile.component.ts

exportclassUserProfileComponent {

constructor(public userService: UserService) { }
}

user-profile.component.html

<inputtype="text" [(ngModel)]="userService.user.name">

In header.component.ts

exportclassHeaderComponent {

constructor(public userService: UserService) { }
}

header.component.html

<span>{{ userService.user.name }}</span>

So the anggular DI will create a singleton UserService and injects the same object to both components. And when you change it in any of them the changes will be shown in other.

Post a Comment for "Changing Value In One Component Affects Another"