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..

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.