surendra kumar
surendra kumar

Reputation: 1780

Call a child method from parent component using reference variable as dynamic

Parent component html.

selectedTab is dynamically changed as 0,1,2,3.

<div fxFlex="50%" class="back_link refresh_icon" (click)="index_[selectedTab].refreshData(activatedRouteSnapshot)">
        </div>
    
    <app-child1 #index_2></app-child1>
    <app-child2 #index_3></app-child2>

I have a method in child2 .ts

 refreshData(test){
        console.log(test)
      }

I am getting the below issue.

Cannot read property '3' of undefined

Upvotes: 0

Views: 595

Answers (2)

Rohit Kumar
Rohit Kumar

Reputation: 36

Use Observer in place of reference variable.

parent component.ts

selectedTabSubject: Subject<any> = new Subject();
onRefreshChild(activatedRouteSnapshot) {
    this.selectedTabSubject.next({ id: activatedRouteSnapshot, index: this.selectedTab });
  }

In parent html

<app-charging-ports [selectedIndex]="selectedTabSubject"></app-charging-ports>

In child.ts

ngAfterViewInit(){
        this.selectedIndex.subscribe(value => { 
          console.log('value is changing', value);
       });
      }
@Input() selectedIndex: Subject<any>;

Upvotes: 2

Gunnar B.
Gunnar B.

Reputation: 2989

You should be able to use @ViewChildren + a function in the parent that you call on click.

Something along the lines

// Parent component

@ViewChildren(child2) tabs: QueryList<child2>;   <= put the actual class name of that child component

onRefreshChild(selectedTab, activatedRouteSnapshot) {
  tabs[selectedTab].refreshData(activatedRouteSnapshot);
}

In the html:

<div fxFlex="50%" class="back_link refresh_icon" (click)="onRefreshChild(selectedTab, activatedRouteSnapshot)">
</div>

If you have selectedTab as a property in the parent component, you of course don't need to pass it, just use this.selectedTab in onRefreshChild.

Upvotes: 0

Related Questions