1

I am trying to call a method from a parent component to child component using template reference variable.. I tried it like below,

navigation.component.html

<button type="button" class="btn btn-primary relative waves-light" (click)="CartTable.loadCart()" mdbWavesEffect>My Cart</button>

<app-cart-table-modal #CartTable></app-cart-table-modal>

cart-table-modal.component.ts

import { Component } from '@angular/core';


@Component({
  selector: 'app-cart-table-modal',
  templateUrl: './cart-table-modal.component.html',
  styleUrls: ['./cart-table-modal.component.scss']
})
export class CartTableModalComponent implements OnInit {

  constructor() {   }

loadCart(){
 console.log('load cart called');
}
}

But I am getting an error as

ERROR TypeError: jit_nodeValue_5(...).loadCart is not a function

Please let me know, how to fix this error.. Thanks in advance..

rahul shalgar
  • 1,198
  • 5
  • 24
  • 39
  • 2
    Can't reproduce: https://stackblitz.com/edit/angular-vjbf4s?file=src%2Fapp%2Fapp.component.html. Post a complete minimal example (as I just did) reproducing the problem. – JB Nizet Jun 19 '18 at 19:13
  • Possible duplicate of [Call child component method from parent class - Angular](https://stackoverflow.com/questions/38974896/call-child-component-method-from-parent-class-angular) – Shift 'n Tab Jun 19 '18 at 19:25

1 Answers1

4

You can call public method from a child component via @ViewChild() decorator.

child.component.ts

export class ChildComponent implements OnInit {

  constructor() {   }

  method1(){
    console.log('logged me!');
  }

}

parent.component.html

<div>
    <button (click)="onLogged()">Logged Me!</button>
    <child-comp #childComp></child-comp>
</div>

parent.component.ts

export class ParentComponent implements OnInit {

  @ViewChild(ChildComponent) child_component: ChildComponent;

  constructor() {   }

  onLogged(){
    this.child_component.method1();
  }

}

Read more about Component interaction in angular.io.

Shift 'n Tab
  • 8,808
  • 12
  • 73
  • 117