首页 > 解决方案 > 使用 EventEmitter 的两个指令之间的角度传递变量

问题描述

我想在 Angular 7 中的两个指令之间传递变量

编辑代码:https ://stackblitz.com/edit/angular-ct49bn

问题是当我在列表中选择一个客户时,发射器无法与其他指令(customer_info.directive.ts)通信

错误是:无法读取未定义的属性“myValueChange”函数“myValueChange”在 customer_info.directive.ts 中定义良好

在 app.module.ts 中声明了指令(import + NgModule)

标签: angularemit

解决方案


请参考https://stackblitz.com/edit/angular-zgyubq?file=src/app/app.component.html

在组件中 -

@ViewChild('custInfo', { static: false }) CustomerInfo: CustomerInfoDirective; 

在模板中 -

<p>
  Choose a customer :
  <selectcustomer 
    (EventCustomerListdirective)="CustomerInfo.myValueChange($event)"> 
  </selectcustomer>
  <CustomerInfo #custInfo></CustomerInfo>
</p>

我认为 Angular 的方法是在组件中使用 @ViewChild 装饰器获取指令的实例,并在模板中使用它,而不是通过依赖注入添加它。


推荐阅读