Search code examples
angularangular2-componentsangular2-output

passing data object through @Output


I'm not getting any errors, but the data isn't passing through to the parent component. The way I'm doing it is a bit different from all the examples I've been finding online so I'm already not too sure about how I have it set up. Here's the code so far.

How I'm calling it in the Child Component

//a variable that stores the fetched data from a group of radio buttons
selected = {value1: '', value2: ''};

//the output variable
@Output() selectedO: EventEmitter<any> = new EventEmitter();

public sendAnswer = (): void => {
     this.selectedO.emit(this.selected);
 }

The Input in the Child Component Template

<input type="radio"
    [attr.name]  = "quesForm.value.name"
    [attr.id]    = "ans.id"
    [attr.value] = "ans.answer"
    (click)      = "getSelected(ans)" //fetches data I want to pass
    (click)      = "sendAnswer()"    //sets fetched data to @Output
    hidden
/>

How I'm calling it in the Parent Component template

<multiple-choice-radio *ngIf="expbTrigger"
    [question]="question01"
    (selectedO)="selectedI" //where I'm trying to pull the data into parent component
 ></multiple-choice-radio>

How I'm callign it in the Parent Component

public selectedI(selected) {
    this.selectedII = selected;
}

selectedII: any; //the variable I'm trying to store it into

This is the best way I could rationalize to try to make this all work. What am I doing wrong here?


Solution

  • The event binding doesn't assign or call if you provide a field or method name, it just executes the expression. The expression therefore needs to include the assignment or call. $event references the emitted value.

    (selectedO)="selectedI = $event" // field
    

    or

    (selectedO)="selectedI($event)" // method