将数据从动态添加的子组件发送到父组件

时间:2018-08-15 21:36:40

标签: angular

我正在将子组件动态添加到父组件。现在,在子组件中,应该有一种方法可以将值发送回父对象,该方法又将其存储到局部变量中。但是我收到“未定义”错误。如果我通过子选择器将子组件添加到模板中,它将起作用。

错误是接受子组件发出的数据的方法无法访问未定义“ save_data”的类变量(this.save_data)。当它在父组件中定义并由父组件中的方法访问时,似乎正在子组件中寻找“ save_data”。

希望我有道理。

子组件:

@Component({
  selector: 'tr[child-component]',
  templateUrl: './stock-item-form.component.html'
})
export class ChildComponent implements OnInit {

  @Input() unique_id:string='';
  @Output() eventActionHandler=new EventEmitter<any>();//

  item_brand: FormControl;

  constructor() {}

  saveRow(event){
    //emits valid data to the parent

    if(this.item_brand.valid){
      let data={'action':'add','data':{}}

      data['data']['brand']=this.item_brand.value;
      this.eventActionHandler.emit(data);

    }

  }


  ngOnInit() {

this.item_brand = new FormControl('', [Validators.required]);

  }

}

child.component.html:

   <td>
  <input type="text" class="form-control" [formControl]="item_brand"> <a href="#" (click)="saveRow($event)"><i class="fa fa-save"></i></a>  
   <div class="alert" *ngIf="!item_brand.valid && item_brand.touched">Enter brand or Unknown</div>

  </td>

现在是父级组件(仅显示相关代码)。错误现在出现在emmitedNewAction方法中,该方法无法访问this.saved_data

直接创建子组件:

 saved_data:any[]=[];

     @ViewChild('stockin_items_containair', {read: ViewContainerRef}) stockin_items_containair: ViewContainerRef; //dynamic stocked in item goes here

addNewChildComponent(){
   //create the child component then subscribe an event to it:

let instance=this.stockin_items_containair.createComponent(this.childComponent);



    instance.instance['eventActionHandler'].subscribe(this.emittedNewRowAction);


  }


 emittedNewRowAction($event){
//data sent from saveRow metod of child component and source of error
 console.log($event)
 console.log(this.saved_data);//saved_data undefined
    }

0 个答案:

没有答案
相关问题