简体   繁体   中英

How to use multiple copies of same child tag having Event Emitter in it at the same time.

I am having a child component which emits data through event emitter.The Emitting data is bind with ngModel in parent. And the emitting method in it is called from parent component. I have created child component because i am having two same form. So i created a single form component and used it twice and binded with their data.

//Child Component Code
import {Component, EventEmitter, Input, Output} from 'angular2/core'

@Component({
  selector: 'child-component',
  template: `
    <input [ngModel]="formObj.title" >
  `
})
export class ChildComponent {
  @Input() formObject: Object;
  @Output() formObjectChange= new EventEmitter();

  emitChangeforParent() {
     this.formObjectChange.emit(newValue);
  }
 }

//Parent Component
 @Component({
    selector: 'parent-component',
    template: `
      <child-component[(formObject)]="doseObject1" #firstForm></child-component>
      <child-component[(formObject)]="doseObject2" #secondForm></child-component>
      <button (click)="save()">Save</button>
    ` 
  })
export class ParentComponent {
  doseObject1 ={title:''};
  doseObject2 ={title:''};

  save(){
     this.firstForm.emitChangeforParent();
     this.secondForm.emitChangeforParent();

     console.log(this.doseObject1);   //Updated data by child is available.But this works when i used single tag. 

But when i use multiple child tag it does not work } }

Problem is that whenever I use single form tag it works fine. The update done by child is reflected here in parent. But when i use same tag tag twice, than on calling its child emitChangeForParent() method does not work.

I think you might be a little confused about how emitChangeForParent should work. This kinda of method would usually be called by the child, and used by the parent.

so the child component would have (change)="emitChangeForParent() , then on the parent you you would have

basically this means whenever the child component calls emit, it passes the data up, and the parent component can catch it by having a callback.

However, In this case I dont think you need to do that. This is most useful for value types like numbers. If you are passing in an refence type, like your json object doseObject1 ={title:''}, the parent object should still have an up to date reference to it.

I think all you need to do to make this work is have you child component template be "" with the banana in the box double binding syntax. Then the parent will still always have an accurate value of doseObject1.title and doseObject2.title

There is no need to emit the data. The double binding syntax returns the changes done in child component to parent component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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