1

Note: since the problem is a little complex, the code is abstracted for readability

We have a <child-component> component template like this:

<select name="someName" #someID ngDefaultControl [(ngModel)]="someModel" (ngModelChange)="onChange(someID.value)">
      <option *ngFor="let a of list" [ngValue]="a.key">{{a.value}}</option>
</select>

And the ts file is with output configuration:

@Component({
  moduleId: module.id,
  selector: 'child-component',
  templateUrl: 'child-component.html',
  outputs: ['someChildEvent']
})

export class ChildComponent {
  someChildEvent = new EventEmitter<string>();
  onChange(value) {
    this.someChildEvent.emit(value);
  }
}

Which we're calling in a <parent-component> like this:

<form #f="ngForm" (submit)="submit(f)" >
<child-component (childEvent)="childData=$event"></child-component>
<input type="submit" value="submit">
</form>

with .ts like:

export class ParentComponent {
    childData;

    submit(f) {
        //How to access childData here?
    }
}
  • Is it the correct implementation of the output configuration in Angular 2?
  • How do we access the value of the select's option from <child-component> on <parent-component>'s form submit to submit(f) function?
Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
  • 2
    `childEvent` needs to be `someChildEvent` – eko May 31 '17 at 10:31
  • @echonax Absolutely correct, however how do we get the value of ``'s `select` element inside the `submit(f)` function? – Zameer Ansari May 31 '17 at 10:39
  • Do you mean like `onChange($event)` instead of `onChange(someID.value)`? – eko May 31 '17 at 10:49
  • @echonax The value of `$event` is coming as `0` when `onChange($event)` is used instead of `onChange(someID.value) ` – Zameer Ansari May 31 '17 at 10:57
  • 1
    That may be because `[ngValue]="a.key"` so `a.key` is `0` I guess? It'll send the whole object with `[ngValue]="a"` – eko May 31 '17 at 10:57
  • 1
    Just a suggestion, instead of using the `outputs` property in the @Component annotation, use the @Output annotation on the someChildEvent property like so: `@Output() someChildEvent = new EventEmitter();` – Martin May 31 '17 at 11:36
  • @Martin Can you elaborate? Why is it good? – Zameer Ansari May 31 '17 at 12:53
  • 1
    It will make your code more readable and maintainable. For instance, if you refactor the name of the `someChildEvent` property you won't need to update the string array in `outputs` that can't be type-checked. – Martin May 31 '17 at 14:05

1 Answers1

2
<child-component (childEvent)="childData=$event"></child-component> 

the event name in here needs to match your method name so it should be:

<child-component (someChildEvent)="childData=$event"></child-component>

and if you like to send the object selected in your select box, change ngValue to that object and the change the model event accordingly:

[ngValue]="a"

(ngModelChange)="onChange($event)"

eko
  • 39,722
  • 10
  • 72
  • 98