I have an Angular2 app which has a parent component (AppComponent) and several child components. One of them (DnDContainer) has an @Output variable like this:
@Output() onDataUpdate: EventEmitter<any> = new EventEmitter();
Inside DnDContainer, there is a button with the following code in its click event:
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'). I'd like to listen to their 'onDataUpdate' output and assign it to a different array (targetItemsA, targetItemsB, etc). 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.
Thanks in advance,
PS: On the tsconfig.spec.json file, I've changed the 'target' property to 'es6' but it still doesn't work.
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.
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>