我想在 Angular 7 中的两个指令之间传递变量
编辑代码 : https://stackblitz.com/edit/angular-ct49bn
问题是当我在列表中选择一个客户时,发射器无法与其他指令(customer_info.directive.ts(通信
错误是:无法读取未定义的属性"myValueChange" 函数"myValueChange"在customer_info.directive.ts中有很好的定义
。在 app.module.ts 中声明指令(import + NgModule(
请参考 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装饰器的指令实例并在模板中使用它,而不是通过依赖注入添加它。
嗨,你的问题是它不是告诉你myValueChange是未定义的,而是告诉你未定义的"myValueChange",这意味着CustomerInfo对象是未定义的。 你在这里只有糟糕的命名...CustomerInfo.myValueChange($event)
应该CustomerInfoDirective.myValueChange($event)
因为你在构造函数中给它起了这个名字:
constructor(
private CustomerListDirective: CustomerListDirective,
private CustomerInfoDirective: CustomerInfoDirective
){}
那么它应该按照您希望的方式工作:)