我正在尝试使用模板引用变量从父组件到子组件调用方法。我尝试如下进行操作,
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');
}
}
但是我得到一个错误
错误TypeError:jit_nodeValue_5(...)。loadCart不是函数
请让我知道如何解决此错误。.预先感谢..
答案 0 :(得分:0)
您可以通过@ViewChild()
装饰器从子组件中调用公共方法。
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();
}
}
在angular.io中了解有关组件交互的更多信息。