Home > Enterprise >  How to detect changes in child component with respect to changes in the base component - Angular
How to detect changes in child component with respect to changes in the base component - Angular

Time:12-27

I have a component profile.component.ts in which there's a variable, this.candidate, which subscribes to and gets updated like this

 this.candidateSub = this.store.select(selectCandidateState).subscribe((candidateState) => {
    this.candidate = candidateState;
 })

This component acts like a base component and there's a child component that extends this component,

export class SkillsComponent extends profile implements OnInit, OnDestroy

Now I want to have another variable in this child component that updates itself whenever this.candidate gets updated in the base component. Something like this:

this.candidateSkills = this.candidate.skills

The problem is I can't get it done simply by declaring this.candidateSkills = this.candidate.skills in ngOnit as it doesn't watch and listen to changes and update itself when this.candidate gets updated in base component.

How should I do it?

CodePudding user response:

In parent component:

this.storeObservable = this.store.select(selectCandidateState)

this.candidateSub = this.storeObservable.subscribe((candidateState) => {
  this.candidate = candidateState;
})

In child component:

this.storeObservable.subscribe((candidateState) => {
  // do something
})
  • Related