Home > Enterprise >  Angular - How to access to child component from grandparent component?
Angular - How to access to child component from grandparent component?

Time:09-30

I have a componentA that has an ng-content. After this I have a componentB inside the component A. The componentB has a componentC in his template.

componentA template:

<ng-content></ng-content>

componentB template:

<componentC></componentC>

componentC template:

<div>
  <span>test</span>
<div>

In my html I have this final solution:

<componentA>
 <componentB></componentB>
</componentA>

I would use a viewChild inside the componentA to find componentC that's inside componentB but it returns undefined

@ViewChild(ComponentC) componentC: ComponentC

How can I solve this issue?

CodePudding user response:

In service:

private sharedValue = new BehaviorSubject('Initial value')
currentSharedValue = this.sharedValue.asObservable()

changeSharedValue(newValue: string) {
  this.sharedValue.next(newValue)
}

If you don't want to set an initial value you can use a regular Subject and if you want to track history a ReplaySubject.

Component changing data:

constructor(
  private dataService: DataService
) { }

changeSharedData(): void {
  this.dataService.changeSharedValue('New Shared Data')
}

Component reading shared data:

value = 'Old Value'
subscription!: Subscription;

constructor(
  private dataService: DataService
) { }

ngOnInit() {
  this.subscription = this.dataService.currentSharedValue.subscribe(newValue => {
    this.value = newValue
  })
}

ngOnDestroy() {
  this.subscription.unsubscribe()
}

CodePudding user response:

You can do it in different way , let child component points to parent !

So assuming ComponentA is parent of ComponentB

So in ComponentA ts define a public variable of ComponentB

myComponent: ComponentB;

At ComponentB constructor inject ComponentA

constructor(parent:ComponentA) { parent.myComponent = this; }

now parent ComponentA can access child componentB

  • Related