Mr.X
Mr.X

Reputation: 31345

Get child component form value in parent component's form submission?

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?
    }
}

Upvotes: 1

Views: 985

Answers (1)

eko
eko

Reputation: 40677

<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)"

Upvotes: 2

Related Questions