[英]Angular 6: How to use template reference variable for calling child method?
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导航.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购物车表-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
错误类型错误:jit_nodeValue_5(...).loadCart 不是函数
Please let me know, how to fix this error.. Thanks in advance..请让我知道,如何解决此错误.. 提前致谢..
You can call public method from a child component via @ViewChild()
decorator.您可以通过
@ViewChild()
装饰器从子组件调用公共方法。
child.component.ts子组件.ts
export class ChildComponent implements OnInit {
constructor() { }
method1(){
console.log('logged me!');
}
}
parent.component.html父组件.html
<div>
<button (click)="onLogged()">Logged Me!</button>
<child-comp #childComp></child-comp>
</div>
parent.component.ts父组件.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 .在angular.io 中阅读有关组件交互的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.