简体   繁体   English

Angular2:我可以用箭头函数而不是方法处理@Output返回值

[英]Angular2: Can I process @Output return value with arrow function instead of method

I have an Angular2 app which has a parent component (AppComponent) and several child components. 我有一个Angular2应用,其中有一个父组件(AppComponent)和几个子组件。 One of them (DnDContainer) has an @Output variable like this: 其中一个(DnDContainer)具有@Output变量,如下所示:

@Output() onDataUpdate: EventEmitter<any> = new EventEmitter();

Inside DnDContainer, there is a button with the following code in its click event: 在DnDContainer内部,单击事件中包含一个带有以下代码的按钮:

onSave(e) {
   this.onDataUpdate.emit(this.data);
   // this.data is just a simple string array
}

Then, from the AppComponent, there are several DnDContainer components (their selector is 'dnd-container'). 然后,在AppComponent中,有几个DnDContainer组件(它们的选择器是“ dnd-container”)。 I'd like to listen to their 'onDataUpdate' output and assign it to a different array (targetItemsA, targetItemsB, etc). 我想听听他们的“ onDataUpdate”输出,并将其分配给另一个数组(targetItemsA,targetItemsB等)。 I'm trying to use a simple syntax like this: 我正在尝试使用这样的简单语法:

<dnd-container (onDataUpdate)="($event) => {targetItemsA = $event}"></dnd-container>
<dnd-container (onDataUpdate)="($event) => {targetItemsB = $event}"></dnd-container>

But it doesn't work, so I had to create an specific method just for assigning an array to another one, like this: 但这是行不通的,因此我不得不创建一种特定的方法,仅用于将一个数组分配给另一个数组,如下所示:

<dnd-container [onDataUpdate)="update('A', $event)"></dnd-container>
<dnd-container [onDataUpdate)="update('B', $event)"></dnd-container>

The method looks like: 该方法如下所示:

update(which, data) {
  switch (which) {
   case 'A':
     this.targetItemsA=data;
     break;
   case 'B':
     this.targetItemsB=data;
     break;
   case 'C':
     this.targetItemsC=data;
     break;
   (ETC...)
  }
}

Is there any simpler way to do this (like the one with arrow function I pointed at the beginning)? 有没有更简单的方法可以做到这一点(例如我一开始指的带有箭头功能的方法)? Sorry if it's too basic, I'm quite new to Angular2. 抱歉,如果太基础了,我对Angular2还是很陌生。

Thanks in advance, 提前致谢,

PS: On the tsconfig.spec.json file, I've changed the 'target' property to 'es6' but it still doesn't work. PS:在tsconfig.spec.json文件上,我已将'target'属性更改为'es6',但仍然无法使用。

Make the following changes: 进行以下更改:

@Output() onDataUpdate: EventEmitter<string[]> = new EventEmitter<string[]>();

Try to avoid using any if you know the type that will be emitted. 如果您知道将要发出的类型,请尝试避免使用any类型。

In the app component you have two options: create a function to handle the event (cleaner template), or directly make operations in it. 在应用程序组件中,您有两个选择:创建一个函数来处理事件(清除程序模板),或直接在其中进行操作。 Apparently you dont want to create a method so the following should work: 显然,您不想创建一个方法,因此以下方法应该起作用:

<dnd-container (onDataUpdate)="targetItemsA = $event"></dnd-container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM